1

Webpack 4 引入了模块类型,允许更好地处理 JSON、CSS、ES6 模块等。

一些加载器,比如messageformat-loader,接受一种类型的源(在本例中为 JSON),但输出另一种类型(在本例中为 JS)。这目前在 Webpack 4 中中断。

ERROR in ./src/messages.json
Module parse failed: Unexpected token v in JSON at position 0
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token v in JSON at position 0
    at JSON.parse (<anonymous>)

加载器如何通知 webpack 模块类型发生变化?

我在加载程序中尝试过this._module.type = 'javascript/auto',但没有效果。

作为一种解决方法,最终用户可以type: 'javascript/auto'为加载器添加到 webpack 配置中,但这似乎是实现细节的泄漏。另外,如果用户希望将此加载器的输出通过管道传输到另一个需要 JS 的加载器中,则它不会起作用。

任何在源类型之间更改的加载器都会受到影响,例如val-loaderto-string-loaderapply-loader等。我认为甚至babel-loader等也会受到影响,因为它们从 ES6 模块转换为 ES5 代码,现在是不同的模块类型。

4

1 回答 1

0

我在copy-files-loader的源代码中找到了解决此问题的方法。本质上,您的加载程序中需要以下内容:

const LoaderDependency = require('webpack/lib/dependencies/LoaderDependency');

module.exports = function (source) {
   const requiredType = 'javascript/auto';
   const factory = this._compilation.dependencyFactories.get(LoaderDependency);
   this._module.type = requiredType;
   this._module.generator = factory.getGenerator(requiredType);
   this._module.parser = factory.getParser(requiredType);

   // do your transforms on `source` here

   return `export default ${JSON.stringify(source)}`;
}
于 2020-03-09T01:01:01.803 回答