简体   繁体   中英

Using a loader inside a webpack plugin

For clarification - this is a question about writing a webpack plugin

How do you use the webpack require inside a webpack plugin?

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?
  });
};

After some searching I saw that the text-extract plugin uses a child compilation to use a compiler inside the plugin:

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

In the following example I am using the my-loader to load and compile the input.js file:

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);
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM