Anik Anik - 2 months ago 54
TypeScript Question

Load a .json file asynchronously with webpack

I am trying to load a .json file asynchronously. There is example for .js file but I am using typescript and can't seem to find a solution.

webpack.config.js

var webpack = require('webpack');

module.exports = {
entry: "./src/app.ts",
output: {
path: './dist',
filename: "bundle.js"
},
resolve: {
extensions: ['', '.ts', '.tsx', '.js', '.jsx', '.json']
},

module: {
loaders: [
{ test: /\.css$/, loader: "style!css" },
{ test: /\.ts$/, loader: 'ts-loader'},
{ test: /\.json$/, loader: 'json-loader'},
{
test: /jquery\.min\.js$/,
loader: 'expose?jQuery'
},
{
test: /jquery\.min\.js$/,
loader: 'expose?$'
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.$': 'jquery'
})
]
};


app.ts

declare var require: {
<T>(path: string): T;
(paths: string[], callback: (...modules: any[]) => void): void;
ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
};


require(['./assets/data.json'], function(data) {
console.log(data); //doesn't log anything.
});


it gives an error in the console,

GET http://localhost:5557/1.bundle.js 404 (Not Found)


However, If I do not try asynchronously, it works fine,

console.log(require('./assets/data.json')); // logs the json just fine


Thanks

Answer

It looks like webpack doesn't know where to find your bundles.

You have to set output.publicPath in your config once you start using bundle splitting. If your dist directory is available in the browser as localhost/dist, you have to set output.publicPath to /dist.

Comments