【问题标题】:Load a .json file asynchronously with webpack使用 webpack 异步加载 .json 文件
【发布时间】:2016-09-17 20:16:00
【问题描述】:

我正在尝试异步加载 .json 文件。有 .js 文件的示例,但我使用的是打字稿,似乎找不到解决方案。

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

谢谢

【问题讨论】:

    标签: typescript webpack ts-loader


    【解决方案1】:

    看起来 webpack 不知道在哪里可以找到你的包。

    一旦开始使用捆绑拆分,您必须在配置中设置output.publicPath。如果你的dist 目录在浏览器中作为localhost/dist 可用,你必须将output.publicPath 设置为/dist/(因为publicPath 将作为webpack 尝试加载的文件的前缀)。

    【讨论】:

    • 在我的配置输出中我添加了 publicPath: './dist',仍然没有改变错误。
    • 不要放./dist,放/dist。 publicPath 在您的浏览器中使用。
    • 如果我输入 /dist 它寻找 localhost:5557/dist1.bundle.js,然后我将值更改为 /dist/,然后它在寻找存在的 localhost:5557/dist/1.bundle.js 时加载。谢谢你的回答:)
    • 酷!我已经改进了我的答案以供将来参考!
    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多