Leg*_*est 18 javascript json angularjs webpack
我的代码在构造之后的某处:
var getMenu = function () {
return window.fetch("portal/content/json/menu.json").then(function (data) {
return data.json();
});
};
Run Code Online (Sandbox Code Playgroud)
我尝试过webpack.config.js这个:
module: {
loaders: [
...
{
test: /\.json$/,
exclude: /node_modules/,
use: [
'file-loader?name=[name].[ext]&outputPath=portal/content/json'
]
},
...
]
}
Run Code Online (Sandbox Code Playgroud)
项目结构:
dist
content
json
menu.json <- this is missing
src
content
json
menu.json <- source file
Run Code Online (Sandbox Code Playgroud)
题:
webpack如何复制src/content/json/menu.json到dist/content/json/menu.json?
Mic*_*ngo 33
您正在使用fetch请求JSON文件,这只会在运行时发生.此外,webpack仅处理导入的任何内容.您希望它处理函数的参数,但是如果webpack这样做,函数的每个参数都将被视为一个模块,并且会破坏该函数的任何其他用途.
如果您希望装载程序启动,则可以导入该文件.
import './portal/content/json/menu.json';
Run Code Online (Sandbox Code Playgroud)
您还可以导入JSON并直接使用它,而不是将其作为运行时获取.Webpack 2 json-loader默认使用所有.json文件.您应该删除.json规则,然后按如下方式导入JSON.
import menu from './portal/content/json/menu.json';
Run Code Online (Sandbox Code Playgroud)
menu是您从getMenu函数获得的JavaScript对象.
如果您希望在运行时/延迟中加载 json,您可以使用 awesome webpack 的动态导入功能:
import(
/* webpackChunkName: "json_menu" */
'./portal/content/json/menu.json'
);
Run Code Online (Sandbox Code Playgroud)
它将返回一个解析为模块对象的 Promise,其中“默认”字段包含您的数据。所以你可能想要这样的东西(使用 es6 看起来非常好):
import(
/* webpackChunkName: "json_menu" */
'./portal/content/json/menu.json'
).then(({default: jsonMenu}) => {
// do whatever you like with your "jsonMenu" variable
console.log('my menu: ', jsonMenu);
});
Run Code Online (Sandbox Code Playgroud)
请注意,动态导入需要一个 babel 插件syntax-dynamic-import,请使用 npm 安装它:
npm i babel-plugin-syntax-dynamic-import -D
Run Code Online (Sandbox Code Playgroud)
祝你今天过得愉快
| 归档时间: |
|
| 查看次数: |
34996 次 |
| 最近记录: |