ProvidePlugin.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ParserHelpers = require("./ParserHelpers");
  7. const ConstDependency = require("./dependencies/ConstDependency");
  8. const NullFactory = require("./NullFactory");
  9. class ProvidePlugin {
  10. constructor(definitions) {
  11. this.definitions = definitions;
  12. }
  13. apply(compiler) {
  14. const definitions = this.definitions;
  15. compiler.plugin("compilation", (compilation, params) => {
  16. compilation.dependencyFactories.set(ConstDependency, new NullFactory());
  17. compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
  18. params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
  19. Object.keys(definitions).forEach(name => {
  20. var request = [].concat(definitions[name]);
  21. var splittedName = name.split(".");
  22. if(splittedName.length > 0) {
  23. splittedName.slice(1).forEach((_, i) => {
  24. const name = splittedName.slice(0, i + 1).join(".");
  25. parser.plugin(`can-rename ${name}`, ParserHelpers.approve);
  26. });
  27. }
  28. parser.plugin(`expression ${name}`, function(expr) {
  29. let nameIdentifier = name;
  30. const scopedName = name.indexOf(".") >= 0;
  31. let expression = `require(${JSON.stringify(request[0])})`;
  32. if(scopedName) {
  33. nameIdentifier = `__webpack_provided_${name.replace(/\./g, "_dot_")}`;
  34. }
  35. if(request.length > 1) {
  36. expression += request.slice(1).map(r => `[${JSON.stringify(r)}]`).join("");
  37. }
  38. if(!ParserHelpers.addParsedVariableToModule(this, nameIdentifier, expression)) {
  39. return false;
  40. }
  41. if(scopedName) {
  42. ParserHelpers.toConstantDependency(nameIdentifier).bind(this)(expr);
  43. }
  44. return true;
  45. });
  46. });
  47. });
  48. });
  49. }
  50. }
  51. module.exports = ProvidePlugin;