index.js 9.7 KB

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