在 webpack 插件中使用加载器 [英] Using a loader inside a webpack plugin

查看:31
本文介绍了在 webpack 插件中使用加载器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

澄清 - 这是一个关于编写 webpack 插件

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

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

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

推荐答案

经过一番搜索,我看到 text-extract 插件使用子编译来使用插件内部的编译器:

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

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

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

这篇关于在 webpack 插件中使用加载器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆