Webpack 4: include many JSON files in output using

2019-08-28 08:37发布

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.

1条回答
Luminary・发光体
2楼-- · 2019-08-28 08:50

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`);
}
查看更多
登录 后发表回答