在 Webpack 中加载静态 JSON 文件 [英] Load static JSON file in Webpack
问题描述
我的代码中有以下构造:
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();
});
};
我在我的 webpack.config.js
中尝试过:
I tried in my webpack.config.js
this:
module: {
loaders: [
...
{
test: /\.json$/,
exclude: /node_modules/,
use: [
'file-loader?name=[name].[ext]&outputPath=portal/content/json'
]
},
...
]
}
项目结构:
dist
content
json
menu.json <- this is missing
src
content
json
menu.json <- source file
问题:
webpack 如何将 src/content/json/menu.json
复制到 dist/content/json/menu.json
?
How can webpack copy src/content/json/menu.json
to dist/content/json/menu.json
?
推荐答案
您正在使用 fetch
来请求 JSON 文件,这只会在运行时发生.此外,webpack 只处理导入的任何内容.您希望它处理函数的参数,但如果 webpack 这样做,函数的每个参数都将被视为模块,这会破坏该函数的任何其他用途.
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.
如果你想让你的加载器启动,你可以导入文件.
If you want your loaders to kick in, you can import the file.
import './portal/content/json/menu.json';
您还可以导入 JSON 并直接使用它,而不是在运行时获取它.Webpack 2 默认为所有
文件.您应该删除 json-loader
>.json.json
规则,然后按如下方式导入 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.
import menu from './portal/content/json/menu.json';
menu
与您从 getMenu
函数中获得的 JavaScript 对象相同.
menu
is the same JavaScript object that you would get from your getMenu
function.
这篇关于在 Webpack 中加载静态 JSON 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!