我正在尝试异步加载.json文件。有.js文件的示例,但我使用的是typescript,似乎无法找到解决方案。
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.
});
它在控制台中出错,
GET http://localhost:5557/1.bundle.js 404 (Not Found)
但是,如果我不尝试异步,它可以正常工作,
console.log(require('./assets/data.json')); // logs the json just fine
由于
答案 0 :(得分:1)
看起来webpack不知道在哪里找到你的捆绑包。
一旦开始使用捆绑拆分,就必须在配置中设置output.publicPath
。如果您的dist
目录在浏览器中显示为localhost/dist
,则必须将output.publicPath
设置为/dist/
(因为publicPath将以webpack尝试加载的文件为前缀)