Webpack 4 - 在加载器中更改模块的类型 [英] Webpack 4 - Change a module's type in a loader
问题描述
Webpack 4 引入了模块类型,可以更好地处理 JSON、CSS、ES6 模块等.
Webpack 4 introduces module types, allowing better handling of JSON, CSS, ES6 modules, etc.
一些加载器,如 messageformat-loader,接受一种类型的源(在这种情况下为 JSON),但输出不同的类型(在本例中为 JS).这目前在 Webpack 4 中被打破了.
Some loaders, like messageformat-loader, take in source of one type (in this case JSON), but output a different type (in this case JS). This currently breaks in 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'
但没有效果.
I tried this._module.type = 'javascript/auto'
in my loader but it had no effect.
作为一种解决方法,最终用户可以将 type: 'javascript/auto'
添加到加载器的 webpack 配置中,但这似乎泄露了实现细节.另外,如果用户希望将此加载器的输出通过管道传输到另一个需要 JS 的加载器中,则它不起作用.
As a workaround, the end user can add type: 'javascript/auto'
to the webpack config for the loader, but this seems like a leak of implementation details. Plus, it wouldn't work in the case where the user wants to pipe the output of this loader into another that's expecting JS.
任何在源类型之间更改的加载器都会受到影响,例如 val-loader, to-string-loader, apply-loader 等.我认为甚至 babel-loader 等会受到影响,因为它们从 ES6 模块转换为 ES5 代码,现在是不同的模块类型.
Any loader that changes between source types will be affected, like val-loader, to-string-loader, apply-loader, etc. I think even babel-loader and the like will be affected since they convert from ES6 modules to ES5 code, which are now different module types.
推荐答案
我在 copy-files-loader.基本上,您的加载器需要以下内容:
I found a work-around to this problem in the source of the copy-files-loader. Essentially you need the following in your 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)}`;
}
这篇关于Webpack 4 - 在加载器中更改模块的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!