防止Webpack的默认加载器运行

时间:2018-05-02 06:25:34

标签: javascript json webpack webpack-loader

Webpack内置了一个JSON加载器。如何编写一个不会尝试在结果上运行内置JSON加载程序的自定义加载程序?

基本上,我希望我的加载器接受一个配置对象(存储在JSON文件中)并从该配置生成源代码,该源代码不再是有效的JSON,它的JavaScript(随后可以通过它提供)巴别装载机)。

这是一个非常愚蠢,做作的例子。源文件是一个JSON文件,但我希望我的加载器的输出改为JS。

装载机

function compile(doc) {
  return `alert(${JSON.stringify(doc.title)})`
}

function myLoader(source) {
  return compile(JSON.parse(source))
}

Webpack config

rules: [
  {
    test: /\.json$/,
    use: [
      'babel-loader',
      'my-loader',
    ],
  },
],

相反,我最终得到了这个错误:

ERROR in ./config.json
Module parse failed: Unexpected token ' in JSON at position 0
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token ' in JSON at position 0
  at JSON.parse (<anonymous>)
  at JsonParser.parse (.../node_modules/webpack/lib/JsonParser.js:15:21)

从堆栈跟踪中可以看出,它来自webpack/lib/JsonParser.js。如何告诉Webpack不要首先运行其内置的JSON解析器,而是将与此规则匹配的JSON文件的处理委托给我的加载器?

1 个答案:

答案 0 :(得分:1)

我想我想出来了,虽然它似乎是一个没有记录的功能(至少,我在configuration docs找不到它。

看起来您可以在Rule对象中传递的属性之一是type。通过将其设置为javascript/auto,您可以覆盖默认的JSON解析器,并将其作为JavaScript解析文件的源。

此属性位于Webpack用于验证配置对象的JSON schema中。

rules: [
  {
    test: /\.json$/,
    use: [
      'babel-loader',
      'my-loader',
    ],
    type: 'javascript/auto',
  },
],
相关问题