如何通过webpack文件加载器加载json?

时间:2019-09-20 16:14:52

标签: webpack webpack-4

我需要通过file-loader加载多个json文件,然后在运行时加载并通过另一个库进行解析,但是webpack将json文件转换为js,并在文件开头添加了'module.exports =...

此配置在构建期间引发错误:

{
  include: ASSETS_SOURCE_PATH,
  use: {
    loader: 'file-loader',
    options: {
      name: '[path][name].[ext]',
    },
  },
},
ERROR in ./src/assets/map/map.json
Module parse failed: Unexpected token m in JSON at position 0 while parsing near 'module.exports = __w...'
File was processed with these loaders:
 * ./node_modules/file-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
SyntaxError: Unexpected token m in JSON at position 0 while parsing near 'module.exports = __w...'

如果我将配置更改为此,我会在运行时解析json时捕获此错误:

{
  test: /\.json$/,
  type: 'javascript/auto',
  include: ASSETS_SOURCE_PATH,
  use: {
    loader: 'file-loader',
    options: {
      name: '[path][name].[ext]',
    },
  },
},
{
  include: ASSETS_SOURCE_PATH,
  use: {
    loader: 'file-loader',
    options: {
      name: '[path][name].[ext]',
    },
  },
},

此文件的内容为module.exports = __webpack_public_path__ + "assets/map/map.json";

UPD:语法import mapTilesJson from '!!file-loader!assets/map/map.json'可以正常工作,但是可能会破坏打字稿的键入。有没有办法在webpack配置中达到相同的效果,而不是内联?

1 个答案:

答案 0 :(得分:0)

我今天遇到同样的问题。一种解决方法是重命名文件并更改其扩展名。例如,从“ map.json”到“ map.json.data”。然后在使用文件加载器加载任何二进制文件时加载“ map.json.data”文件。