简体   繁体   English

编写webpack加载器 - 注入一次代码

[英]Writing a webpack loader - inject code once

I'm trying to write a webpack loader, and one of the requirements is that I need to inject code ONCE into each bundle. 我正在尝试编写一个webpack加载器,其中一个要求是我需要将代码ONCE注入每个bundle。

Is there a way in the loader to detect if the module I'm processing is an entry point? 加载器中是否有一种方法可以检测我正在处理的模块是否是一个入口点? If not, is there an easy way to inject code once per bundle? 如果没有,是否有一种简单的方法可以为每个包注入一次代码?

You can inject code like you inject code normally. 您可以像注入代码一样注入代码。 Your loader should return the transformed source with a require to the code you need to inject once. 您的加载器应该将带有需求的转换源返回到您需要注入一次的代码。 Webpack's documentation covers this referring to this common code as a runtime for the loader. Webpack的文档将此公共代码称为加载器的运行时。 http://webpack.github.io/docs/how-to-write-a-loader.html#extract-common-code http://webpack.github.io/docs/how-to-write-a-loader.html#extract-common-code

 var loaderUtils = require('loader-utils'); module.exports = function(content) { return "require(" + loaderUtils.stringifyRequest(this, "!" + require.resolve("./runtime")) + ");\\n\\n" + content; }; 

Is this helpful? 这有用吗?

module.exports = function (content) {

  if (this.options.entry == this.resourcePath)
    content = 'var newCode = 10;\r\n\r\n' + content;

  return content;

};

I am using this to inject code on the entry file only. 我使用它只在入口文件上注入代码。

You can't use loaders on entry points (as well as you can't depends on entry points). 您不能在入口点使用装载机(并且您不能依赖入口点)。 So if you want to inject some code through the loader you have to require on it in each entry point. 因此,如果您想通过加载器注入一些代码,则必须在每个入口点对其进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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