Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
  });
};
like image 347
jantimon Avatar asked Mar 11 '15 13:03

jantimon


People also ask

When using webpack Why would you need to use a loader?

Webpack enables use of loaders to preprocess files. This allows you to bundle any static resource way beyond JavaScript. You can easily write your own loaders using Node. js.

What is the difference between loader and plugin in webpack?

Loaders work at the individual file level during or before the bundle is generated. Plugins: Plugins work at bundle or chunk level and usually work at the end of the bundle generation process.

How do loaders work webpack?

The idea behind Webpack loaders is to provide multiple ways to handle some resource or asset - whether that's a javascript module, a CSS stylesheet, or an image. The loader is responsible for parsing/processing the resource, which might do any of the following: Transpile it into another language (e.g. babel-loader)


1 Answers

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);
  });
};
like image 182
jantimon Avatar answered Sep 28 '22 05:09

jantimon