【问题标题】:Webpack 4 - Change a module's type in a loaderWebpack 4 - 在加载器中更改模块的类型
【发布时间】:2018-03-20 23:45:39
【问题描述】:

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 代码,现在是不同的模块类型。

【问题讨论】:

标签: webpack webpack-loader


【解决方案1】:

我在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)}`;
}

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2016-02-26
    • 1970-01-01
    • 2020-06-09
    • 2018-01-11
    相关资源
    最近更新 更多