index.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. let babel;
  2. try {
  3. babel = require("@babel/core");
  4. } catch (err) {
  5. if (err.code === "MODULE_NOT_FOUND") {
  6. err.message += "\n babel-loader@9 requires Babel 7.12+ (the package '@babel/core'). " + "If you'd like to use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.";
  7. }
  8. throw err;
  9. }
  10. // Since we've got the reverse bridge package at @babel/core@6.x, give
  11. // people useful feedback if they try to use it alongside babel-loader.
  12. if (/^6\./.test(babel.version)) {
  13. throw new Error("\n babel-loader@9 will not work with the '@babel/core@6' bridge package. " + "If you want to use Babel 6.x, install 'babel-loader@7'.");
  14. }
  15. const {
  16. version
  17. } = require("../package.json");
  18. const cache = require("./cache");
  19. const transform = require("./transform");
  20. const injectCaller = require("./injectCaller");
  21. const schema = require("./schema");
  22. const {
  23. isAbsolute
  24. } = require("path");
  25. const validateOptions = require("schema-utils").validate;
  26. function subscribe(subscriber, metadata, context) {
  27. if (context[subscriber]) {
  28. context[subscriber](metadata);
  29. }
  30. }
  31. module.exports = makeLoader();
  32. module.exports.custom = makeLoader;
  33. function makeLoader(callback) {
  34. const overrides = callback ? callback(babel) : undefined;
  35. return function (source, inputSourceMap) {
  36. // Make the loader async
  37. const callback = this.async();
  38. loader.call(this, source, inputSourceMap, overrides).then(args => callback(null, ...args), err => callback(err));
  39. };
  40. }
  41. async function loader(source, inputSourceMap, overrides) {
  42. const filename = this.resourcePath;
  43. const logger = typeof this.getLogger === "function" ? this.getLogger("babel-loader") : {
  44. debug: () => {}
  45. };
  46. let loaderOptions = this.getOptions();
  47. validateOptions(schema, loaderOptions, {
  48. name: "Babel loader"
  49. });
  50. if (loaderOptions.customize != null) {
  51. if (typeof loaderOptions.customize !== "string") {
  52. throw new Error("Customized loaders must be implemented as standalone modules.");
  53. }
  54. if (!isAbsolute(loaderOptions.customize)) {
  55. throw new Error("Customized loaders must be passed as absolute paths, since " + "babel-loader has no way to know what they would be relative to.");
  56. }
  57. if (overrides) {
  58. throw new Error("babel-loader's 'customize' option is not available when already " + "using a customized babel-loader wrapper.");
  59. }
  60. logger.debug(`loading customize override: '${loaderOptions.customize}'`);
  61. let override = require(loaderOptions.customize);
  62. if (override.__esModule) override = override.default;
  63. if (typeof override !== "function") {
  64. throw new Error("Custom overrides must be functions.");
  65. }
  66. logger.debug("applying customize override to @babel/core");
  67. overrides = override(babel);
  68. }
  69. let customOptions;
  70. if (overrides && overrides.customOptions) {
  71. logger.debug("applying overrides customOptions() to loader options");
  72. const result = await overrides.customOptions.call(this, loaderOptions, {
  73. source,
  74. map: inputSourceMap
  75. });
  76. customOptions = result.custom;
  77. loaderOptions = result.loader;
  78. }
  79. // Deprecation handling
  80. if ("forceEnv" in loaderOptions) {
  81. console.warn("The option `forceEnv` has been removed in favor of `envName` in Babel 7.");
  82. }
  83. if (typeof loaderOptions.babelrc === "string") {
  84. console.warn("The option `babelrc` should not be set to a string anymore in the babel-loader config. " + "Please update your configuration and set `babelrc` to true or false.\n" + "If you want to specify a specific babel config file to inherit config from " + "please use the `extends` option.\nFor more information about this options see " + "https://babeljs.io/docs/core-packages/#options");
  85. }
  86. logger.debug("normalizing loader options");
  87. // Standardize on 'sourceMaps' as the key passed through to Webpack, so that
  88. // users may safely use either one alongside our default use of
  89. // 'this.sourceMap' below without getting error about conflicting aliases.
  90. if (Object.prototype.hasOwnProperty.call(loaderOptions, "sourceMap") && !Object.prototype.hasOwnProperty.call(loaderOptions, "sourceMaps")) {
  91. loaderOptions = Object.assign({}, loaderOptions, {
  92. sourceMaps: loaderOptions.sourceMap
  93. });
  94. delete loaderOptions.sourceMap;
  95. }
  96. const programmaticOptions = Object.assign({}, loaderOptions, {
  97. filename,
  98. inputSourceMap: inputSourceMap || loaderOptions.inputSourceMap,
  99. // Set the default sourcemap behavior based on Webpack's mapping flag,
  100. // but allow users to override if they want.
  101. sourceMaps: loaderOptions.sourceMaps === undefined ? this.sourceMap : loaderOptions.sourceMaps,
  102. // Ensure that Webpack will get a full absolute path in the sourcemap
  103. // so that it can properly map the module back to its internal cached
  104. // modules.
  105. sourceFileName: filename
  106. });
  107. // Remove loader related options
  108. delete programmaticOptions.customize;
  109. delete programmaticOptions.cacheDirectory;
  110. delete programmaticOptions.cacheIdentifier;
  111. delete programmaticOptions.cacheCompression;
  112. delete programmaticOptions.metadataSubscribers;
  113. logger.debug("resolving Babel configs");
  114. const config = await babel.loadPartialConfigAsync(injectCaller(programmaticOptions, this.target));
  115. if (config) {
  116. let options = config.options;
  117. if (overrides && overrides.config) {
  118. logger.debug("applying overrides config() to Babel config");
  119. options = await overrides.config.call(this, config, {
  120. source,
  121. map: inputSourceMap,
  122. customOptions
  123. });
  124. }
  125. if (options.sourceMaps === "inline") {
  126. // Babel has this weird behavior where if you set "inline", we
  127. // inline the sourcemap, and set 'result.map = null'. This results
  128. // in bad behavior from Babel since the maps get put into the code,
  129. // which Webpack does not expect, and because the map we return to
  130. // Webpack is null, which is also bad. To avoid that, we override the
  131. // behavior here so "inline" just behaves like 'true'.
  132. options.sourceMaps = true;
  133. }
  134. const {
  135. cacheDirectory = null,
  136. cacheIdentifier = JSON.stringify({
  137. options,
  138. "@babel/core": transform.version,
  139. "@babel/loader": version
  140. }),
  141. cacheCompression = true,
  142. metadataSubscribers = []
  143. } = loaderOptions;
  144. let result;
  145. if (cacheDirectory) {
  146. logger.debug("cache is enabled");
  147. result = await cache({
  148. source,
  149. options,
  150. transform,
  151. cacheDirectory,
  152. cacheIdentifier,
  153. cacheCompression,
  154. logger
  155. });
  156. } else {
  157. logger.debug("cache is disabled, applying Babel transform");
  158. result = await transform(source, options);
  159. }
  160. config.files.forEach(configFile => {
  161. this.addDependency(configFile);
  162. logger.debug(`added '${configFile}' to webpack dependencies`);
  163. });
  164. if (result) {
  165. if (overrides && overrides.result) {
  166. logger.debug("applying overrides result() to Babel transform results");
  167. result = await overrides.result.call(this, result, {
  168. source,
  169. map: inputSourceMap,
  170. customOptions,
  171. config,
  172. options
  173. });
  174. }
  175. const {
  176. code,
  177. map,
  178. metadata,
  179. externalDependencies
  180. } = result;
  181. externalDependencies?.forEach(dep => {
  182. this.addDependency(dep);
  183. logger.debug(`added '${dep}' to webpack dependencies`);
  184. });
  185. metadataSubscribers.forEach(subscriber => {
  186. subscribe(subscriber, metadata, this);
  187. logger.debug(`invoked metadata subscriber '${String(subscriber)}'`);
  188. });
  189. return [code, map];
  190. }
  191. }
  192. // If the file was ignored, pass through the original content.
  193. return [source, inputSourceMap];
  194. }