在webpack插件中使用加载器

jan*_*mon 11 javascript webpack

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

你如何require在webpack插件中使用webpack?

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?
  });
};
Run Code Online (Sandbox Code Playgroud)

jan*_*mon 12

经过一些搜索后,我看到text-extract插件使用子编译来使用插件中的编译器:

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);
  });
};
Run Code Online (Sandbox Code Playgroud)