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?
});
};
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.
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.
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)
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);
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With