Webpack:通过文件加载器复制JSON文件 [英] Webpack: Copy JSON-files via file-loader
问题描述
我在编译时使用Webpack的module.loaders
和file-loader
复制几个js文件:
I am using Webpack's module.loaders
and file-loader
to copy several js-files when compiling:
module.loaders = [
{ test: /app\/locale\/moment\/.*\.js$/, loader: "file-loader?name=locale/moment/[name].[ext]" }
];
这对我来说很好.
我想对JSON文件做同样的事情:
This works fine for me.
I want to do the same thing with JSON-files:
module.loaders = [
{ test: /app\/locale\/.*\.json$/, loader: "file-loader?name=locale/[name].[ext]" }
];
但是这次它什么也没做.
为什么使用文件加载器时,Webpack为什么在js文件和json文件之间有所区别?
But this time it doesn't do anything.
Why does Webpack make a difference between js- and json-files when using the file-loader?
推荐答案
这是对我的答案我的答案的改编自己也有类似的问题.
This is an adaptation of my answer to my own similar question.
您可以通过将以下代码添加到Webpack配置中来通过文件加载器复制JSON文件:
You can copy JSON files via file-loader by adding the following code to you Webpack config:
module: {
rules: [
// ...
{
test: /\.json$/,
loader: 'file-loader?name=[name].json'
}
// ...
]
}
这里有两个细微差别:1)文件加载器仅复制在代码中某处导入/需要的文件,以及2)文件加载器发出文件加载路径,而不是文件内容本身.
There are two nuances here: 1) file-loader will only copy files that are imported/required somewhere in your code and 2) file-loader emits a path to where the file was loaded, rather than the contents of the file itself.
因此,要复制JSON文件,您首先需要将其导入,例如:
So, to copy a JSON file you'll first need to import it, for example:
const configFile = require('../config.json');
由于文件加载器会发出指向文件加载器的路径,因此configFile
的值为"/config.json"
.
Since file-loader emits a path to the where the file was loader, configFile
has the value "/config.json"
.
现在可以随心所欲地加载JSON文件的内容,例如使用 jsonfile
Now the contents of the JSON file can be loaded however you like, such as with jsonfile
jsonfile.readFile(configFile, function(err, obj) {
console.log(obj);
});
或使用Angular的 HTTP 包
or with Angular's HTTP package
http.get(configFile).map(res => res.json()).catch((error: any): any => {
// ...
}).subscribe(obj => {
console.log(obj);
});
这篇关于Webpack:通过文件加载器复制JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!