[翻译]  Load static JSON file in Webpack

[CHINESE]  在Webpack中加载静态JSON文件


I have somewhere in my code following construction:

我的代码中有一些在构造之后:

var getMenu = function () {
    return window.fetch("portal/content/json/menu.json").then(function (data) {
        return data.json();
    });
};

I tried in my webpack.config.js this:

我尝试在我的webpack.config.js中:

module: {
    loaders: [
        ...
        {
            test: /\.json$/,
            exclude: /node_modules/,
            use: [
                'file-loader?name=[name].[ext]&outputPath=portal/content/json'
            ]
        },
        ...
   ]
}

Project structure:

项目结构:

dist
  content
     json
        menu.json <- this is missing

src
  content
     json
       menu.json <- source file

Question:

题:

How can webpack copy src/content/json/menu.json to dist/content/json/menu.json ?

webpack如何将src / content / json / menu.json复制到dist / content / json / menu.json?

1 个解决方案

#1


18  

You're using fetch to request a JSON file and that will only happen at runtime. Furthermore, webpack only processes anything that is imported. You expected it to handle an argument to a function, but if webpack did that, every argument to a function would be considered a module and that breaks any other use for that function.

您正在使用fetch来请求JSON文件,这只会在运行时发生。此外,webpack仅处理导入的任何内容。您希望它处理函数的参数,但是如果webpack这样做,函数的每个参数都将被视为一个模块,并且会破坏该函数的任何其他用途。

If you want your loaders to kick in, you can import the file.

如果您希望装载程序启动,则可以导入该文件。

import './portal/content/json/menu.json';

You can also import the JSON and use it directly instead of fetching it a runtime. Webpack 2 uses json-loader by default for all .json files. You should remove the .json rule and you would import the JSON as follows.

您还可以导入JSON并直接使用它,而不是将其作为运行时获取。对于所有.json文件,Webpack 2默认使用json-loader。您应该删除.json规则,然后按如下方式导入JSON。

import menu from './portal/content/json/menu.json';

menu is the same JavaScript object that you would get from your getMenu function.

menu是与getMenu函数相同的JavaScript对象。


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2018 ITdaan.com 粤ICP备14056181号