在 webpack 插件中使用加载器

Using a loader inside a webpack plugin

本文关键字:加载 webpack 插件      更新时间:2023-09-26

为了澄清 - 这是一个关于编写 webpack 插件的问题

如何在 webpack 插件中使用 webpack require

MyPlugin.prototype.apply = function(compiler) {
  var self = this;
  compiler.plugin('emit', function(compilation, callback) {
     var file = 'example.css';
     compilation.fileDependencies.push(file);
     var loaderResult = require('style!css!' + file); // <-- is there any way to make this possible?
  });
};

经过一番搜索,我看到文本提取插件使用子编译来使用插件内部的编译器:

https://github.com/SanderSpies/extract-text-webpack-plugin/blob/be6484f00c46799280b9ec28946faf935cb9ae63/loader.js#L65

在下面的示例中,我使用 my-loader 加载和编译 input.js 文件:

MyPlugin.prototype.apply = function(compiler) {
  compiler.plugin('make', function(compilation, callback) {
    var outputOptions = {
      filename: 'output.js',
      publicPath: compilation.outputOptions.publicPath
    };
    var childCompiler = compilation.createChildCompiler('MyPluginCompilation', outputOptions);
    childCompiler.apply(new NodeTemplatePlugin(outputOptions));
    childCompiler.apply(new LibraryTemplatePlugin('result', 'var'));
    childCompiler.apply(new NodeTargetPlugin());
    childCompiler.apply(new SingleEntryPlugin(this.context, 'my-loader!input.js'));
    childCompiler.runAsChild(callback);
  });
};