简体   繁体   中英

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.

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. 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.

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