Webpack 4:使用文件加载器在输出中包含许多JSON文件 [英] Webpack 4: include many JSON files in output using file-loader
问题描述
我正在使用Webpack 4,并试图实现以下目标:
collections/
文件夹包含许多个JSON文件,我希望这些文件以[name].[chunkhash].json
形式(或这种形式的变体)包含在我的输出文件夹中.
在JS文件中,我想动态地要求它们,例如
import(`collections/${name}.json`)
.此外,我希望此require语句能够解析为该块的URL,因此我可以使用Backbone来获取它.
似乎file-loader
将是它的理想选择,但是我很难使它与JSON文件一起使用.
webpack.config.js
{
test: [
/\.json$/
],
type: 'javascript/auto',
include: [/generated/],
loader: 'file-loader'
}
骨干模型
url: function() {
return import(`collections/${this.get('id')}.json`);
}
我希望将此处的import
语句替换为输出文件夹中JSON文件的URL.在这里应该使用哪种导入样式?
P.S.我想避免使用copy-webpack-plugin
.
此处的解决方案是使用require()
代替import()
,这将同步解析为资产的URL:>
骨干模型
url: function() {
return require(`collections/${this.get('id')}.json`);
}
I am using Webpack 4, and am trying to achieve the following:
The collections/
folder contains many JSON files, which I want to include in my output folder in the form [name].[chunkhash].json
(or a variation of this).
In the JS file, I want to require them dynamically, e.g.
import(`collections/${name}.json`)
. Furthermore, I would like this require statement to resolve to the URL for the chunk, so I can fetch it using Backbone.
Seems file-loader
would be the perfect candidate for it, but I'm having a hard time making it work with JSON files.
webpack.config.js
{
test: [
/\.json$/
],
type: 'javascript/auto',
include: [/generated/],
loader: 'file-loader'
}
Backbone model
url: function() {
return import(`collections/${this.get('id')}.json`);
}
I'd like the import
statement here to be replaced with the URL of the JSON file in the output folder. What style of import should be used here?
P.S. I would like to avoid copy-webpack-plugin
for this.
The solution here is to use require()
instead of import()
, which will synchronously resolve to the asset's URL:
Backbone model
url: function() {
return require(`collections/${this.get('id')}.json`);
}
这篇关于Webpack 4:使用文件加载器在输出中包含许多JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!