loader.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. "use strict";
  2. const path = require("path");
  3. const {
  4. findModuleById,
  5. evalModuleCode,
  6. AUTO_PUBLIC_PATH,
  7. ABSOLUTE_PUBLIC_PATH,
  8. BASE_URI,
  9. SINGLE_DOT_PATH_SEGMENT,
  10. stringifyRequest,
  11. stringifyLocal
  12. } = require("./utils");
  13. const schema = require("./loader-options.json");
  14. const MiniCssExtractPlugin = require("./index");
  15. /** @typedef {import("schema-utils/declarations/validate").Schema} Schema */
  16. /** @typedef {import("webpack").Compiler} Compiler */
  17. /** @typedef {import("webpack").Compilation} Compilation */
  18. /** @typedef {import("webpack").Chunk} Chunk */
  19. /** @typedef {import("webpack").Module} Module */
  20. /** @typedef {import("webpack").sources.Source} Source */
  21. /** @typedef {import("webpack").AssetInfo} AssetInfo */
  22. /** @typedef {import("webpack").NormalModule} NormalModule */
  23. /** @typedef {import("./index.js").LoaderOptions} LoaderOptions */
  24. /** @typedef {{ [key: string]: string | function }} Locals */
  25. /** @typedef {any} TODO */
  26. /**
  27. * @typedef {Object} Dependency
  28. * @property {string} identifier
  29. * @property {string | null} context
  30. * @property {Buffer} content
  31. * @property {string} media
  32. * @property {string} [supports]
  33. * @property {string} [layer]
  34. * @property {Buffer} [sourceMap]
  35. */
  36. /**
  37. * @param {string} content
  38. * @param {{ loaderContext: import("webpack").LoaderContext<LoaderOptions>, options: LoaderOptions, locals: Locals | undefined }} context
  39. * @returns {string}
  40. */
  41. function hotLoader(content, context) {
  42. const localsJsonString = JSON.stringify(JSON.stringify(context.locals));
  43. return `${content}
  44. if(module.hot) {
  45. (function() {
  46. var localsJsonString = ${localsJsonString};
  47. // ${Date.now()}
  48. var cssReload = require(${stringifyRequest(context.loaderContext, path.join(__dirname, "hmr/hotModuleReplacement.js"))})(module.id, ${JSON.stringify(context.options)});
  49. // only invalidate when locals change
  50. if (
  51. module.hot.data &&
  52. module.hot.data.value &&
  53. module.hot.data.value !== localsJsonString
  54. ) {
  55. module.hot.invalidate();
  56. } else {
  57. module.hot.accept();
  58. }
  59. module.hot.dispose(function(data) {
  60. data.value = localsJsonString;
  61. cssReload();
  62. });
  63. })();
  64. }
  65. `;
  66. }
  67. /**
  68. * @this {import("webpack").LoaderContext<LoaderOptions>}
  69. * @param {string} request
  70. */
  71. function pitch(request) {
  72. if (this._compiler && this._compiler.options && this._compiler.options.experiments && this._compiler.options.experiments.css && this._module && (this._module.type === "css" || this._module.type === "css/auto" || this._module.type === "css/global" || this._module.type === "css/module")) {
  73. this.emitWarning(new Error('You can\'t use `experiments.css` (`experiments.futureDefaults` enable built-in CSS support by default) and `mini-css-extract-plugin` together, please set `experiments.css` to `false` or set `{ type: "javascript/auto" }` for rules with `mini-css-extract-plugin` in your webpack config (now `mini-css-extract-plugin` does nothing).'));
  74. return;
  75. }
  76. // @ts-ignore
  77. const options = this.getOptions( /** @type {Schema} */schema);
  78. const emit = typeof options.emit !== "undefined" ? options.emit : true;
  79. const callback = this.async();
  80. const optionsFromPlugin = /** @type {TODO} */this[MiniCssExtractPlugin.pluginSymbol];
  81. if (!optionsFromPlugin) {
  82. callback(new Error("You forgot to add 'mini-css-extract-plugin' plugin (i.e. `{ plugins: [new MiniCssExtractPlugin()] }`), please read https://github.com/webpack-contrib/mini-css-extract-plugin#getting-started"));
  83. return;
  84. }
  85. const {
  86. webpack
  87. } = /** @type {Compiler} */this._compiler;
  88. /**
  89. * @param {TODO} originalExports
  90. * @param {Compilation} [compilation]
  91. * @param {{ [name: string]: Source }} [assets]
  92. * @param {Map<string, AssetInfo>} [assetsInfo]
  93. * @returns {void}
  94. */
  95. const handleExports = (originalExports, compilation, assets, assetsInfo) => {
  96. /** @type {Locals | undefined} */
  97. let locals;
  98. let namedExport;
  99. const esModule = typeof options.esModule !== "undefined" ? options.esModule : true;
  100. /**
  101. * @param {Dependency[] | [null, object][]} dependencies
  102. */
  103. const addDependencies = dependencies => {
  104. if (!Array.isArray(dependencies) && dependencies != null) {
  105. throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`);
  106. }
  107. const identifierCountMap = new Map();
  108. let lastDep;
  109. for (const dependency of dependencies) {
  110. if (!( /** @type {Dependency} */dependency.identifier) || !emit) {
  111. // eslint-disable-next-line no-continue
  112. continue;
  113. }
  114. const count = identifierCountMap.get( /** @type {Dependency} */dependency.identifier) || 0;
  115. const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack);
  116. /** @type {NormalModule} */
  117. this._module.addDependency(lastDep = new CssDependency( /** @type {Dependency} */
  118. dependency, /** @type {Dependency} */
  119. dependency.context, count));
  120. identifierCountMap.set( /** @type {Dependency} */
  121. dependency.identifier, count + 1);
  122. }
  123. if (lastDep && assets) {
  124. lastDep.assets = assets;
  125. lastDep.assetsInfo = assetsInfo;
  126. }
  127. };
  128. try {
  129. // eslint-disable-next-line no-underscore-dangle
  130. const exports = originalExports.__esModule ? originalExports.default : originalExports;
  131. namedExport =
  132. // eslint-disable-next-line no-underscore-dangle
  133. originalExports.__esModule && (!originalExports.default || !("locals" in originalExports.default));
  134. if (namedExport) {
  135. Object.keys(originalExports).forEach(key => {
  136. if (key !== "default") {
  137. if (!locals) {
  138. locals = {};
  139. }
  140. /** @type {Locals} */
  141. locals[key] = originalExports[key];
  142. }
  143. });
  144. } else {
  145. locals = exports && exports.locals;
  146. }
  147. /** @type {Dependency[] | [null, object][]} */
  148. let dependencies;
  149. if (!Array.isArray(exports)) {
  150. dependencies = [[null, exports]];
  151. } else {
  152. dependencies = exports.map(([id, content, media, sourceMap, supports, layer]) => {
  153. let identifier = id;
  154. let context;
  155. if (compilation) {
  156. const module = /** @type {Module} */
  157. findModuleById(compilation, id);
  158. identifier = module.identifier();
  159. ({
  160. context
  161. } = module);
  162. } else {
  163. // TODO check if this context is used somewhere
  164. context = this.rootContext;
  165. }
  166. return {
  167. identifier,
  168. context,
  169. content: Buffer.from(content),
  170. media,
  171. supports,
  172. layer,
  173. sourceMap: sourceMap ? Buffer.from(JSON.stringify(sourceMap)) :
  174. // eslint-disable-next-line no-undefined
  175. undefined
  176. };
  177. });
  178. }
  179. addDependencies(dependencies);
  180. } catch (e) {
  181. callback( /** @type {Error} */e);
  182. return;
  183. }
  184. const result = function makeResult() {
  185. const defaultExport = typeof options.defaultExport !== "undefined" ? options.defaultExport : false;
  186. if (locals) {
  187. if (namedExport) {
  188. const identifiers = Array.from(function* generateIdentifiers() {
  189. let identifierId = 0;
  190. for (const key of Object.keys(locals)) {
  191. identifierId += 1;
  192. yield [`_${identifierId.toString(16)}`, key];
  193. }
  194. }());
  195. const localsString = identifiers.map(([id, key]) => `\nvar ${id} = ${stringifyLocal( /** @type {Locals} */locals[key])};`).join("");
  196. const exportsString = `export { ${identifiers.map(([id, key]) => `${id} as ${JSON.stringify(key)}`).join(", ")} }`;
  197. return defaultExport ? `${localsString}\n${exportsString}\nexport default { ${identifiers.map(([id, key]) => `${JSON.stringify(key)}: ${id}`).join(", ")} }\n` : `${localsString}\n${exportsString}\n`;
  198. }
  199. return `\n${esModule ? "export default" : "module.exports = "} ${JSON.stringify(locals)};`;
  200. } else if (esModule) {
  201. return defaultExport ? "\nexport {};export default {};" : "\nexport {};";
  202. }
  203. return "";
  204. }();
  205. let resultSource = `// extracted by ${MiniCssExtractPlugin.pluginName}`;
  206. // only attempt hotreloading if the css is actually used for something other than hash values
  207. resultSource += this.hot && emit ? hotLoader(result, {
  208. loaderContext: this,
  209. options,
  210. locals
  211. }) : result;
  212. callback(null, resultSource);
  213. };
  214. let {
  215. publicPath
  216. } = /** @type {Compilation} */
  217. this._compilation.outputOptions;
  218. if (typeof options.publicPath === "string") {
  219. // eslint-disable-next-line prefer-destructuring
  220. publicPath = options.publicPath;
  221. } else if (typeof options.publicPath === "function") {
  222. publicPath = options.publicPath(this.resourcePath, this.rootContext);
  223. }
  224. if (publicPath === "auto") {
  225. publicPath = AUTO_PUBLIC_PATH;
  226. }
  227. if (typeof optionsFromPlugin.experimentalUseImportModule === "undefined" && typeof this.importModule === "function" || optionsFromPlugin.experimentalUseImportModule) {
  228. if (!this.importModule) {
  229. callback(new Error("You are using 'experimentalUseImportModule' but 'this.importModule' is not available in loader context. You need to have at least webpack 5.33.2."));
  230. return;
  231. }
  232. let publicPathForExtract;
  233. if (typeof publicPath === "string") {
  234. const isAbsolutePublicPath = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/.test(publicPath);
  235. publicPathForExtract = isAbsolutePublicPath ? publicPath : `${ABSOLUTE_PUBLIC_PATH}${publicPath.replace(/\./g, SINGLE_DOT_PATH_SEGMENT)}`;
  236. } else {
  237. publicPathForExtract = publicPath;
  238. }
  239. this.importModule(`${this.resourcePath}.webpack[javascript/auto]!=!!!${request}`, {
  240. layer: options.layer,
  241. publicPath: ( /** @type {string} */publicPathForExtract),
  242. baseUri: `${BASE_URI}/`
  243. },
  244. /**
  245. * @param {Error | null | undefined} error
  246. * @param {object} exports
  247. */
  248. (error, exports) => {
  249. if (error) {
  250. callback(error);
  251. return;
  252. }
  253. handleExports(exports);
  254. });
  255. return;
  256. }
  257. const loaders = this.loaders.slice(this.loaderIndex + 1);
  258. this.addDependency(this.resourcePath);
  259. const childFilename = "*";
  260. const outputOptions = {
  261. filename: childFilename,
  262. publicPath
  263. };
  264. const childCompiler = /** @type {Compilation} */
  265. this._compilation.createChildCompiler(`${MiniCssExtractPlugin.pluginName} ${request}`, outputOptions);
  266. // The templates are compiled and executed by NodeJS - similar to server side rendering
  267. // Unfortunately this causes issues as some loaders require an absolute URL to support ES Modules
  268. // The following config enables relative URL support for the child compiler
  269. childCompiler.options.module = {
  270. ...childCompiler.options.module
  271. };
  272. childCompiler.options.module.parser = {
  273. ...childCompiler.options.module.parser
  274. };
  275. childCompiler.options.module.parser.javascript = {
  276. ...childCompiler.options.module.parser.javascript,
  277. url: "relative"
  278. };
  279. const {
  280. NodeTemplatePlugin
  281. } = webpack.node;
  282. const {
  283. NodeTargetPlugin
  284. } = webpack.node;
  285. // @ts-ignore
  286. new NodeTemplatePlugin(outputOptions).apply(childCompiler);
  287. new NodeTargetPlugin().apply(childCompiler);
  288. const {
  289. EntryOptionPlugin
  290. } = webpack;
  291. const {
  292. library: {
  293. EnableLibraryPlugin
  294. }
  295. } = webpack;
  296. new EnableLibraryPlugin("commonjs2").apply(childCompiler);
  297. EntryOptionPlugin.applyEntryOption(childCompiler, this.context, {
  298. child: {
  299. library: {
  300. type: "commonjs2"
  301. },
  302. import: [`!!${request}`]
  303. }
  304. });
  305. const {
  306. LimitChunkCountPlugin
  307. } = webpack.optimize;
  308. new LimitChunkCountPlugin({
  309. maxChunks: 1
  310. }).apply(childCompiler);
  311. const {
  312. NormalModule
  313. } = webpack;
  314. childCompiler.hooks.thisCompilation.tap(`${MiniCssExtractPlugin.pluginName} loader`,
  315. /**
  316. * @param {Compilation} compilation
  317. */
  318. compilation => {
  319. const normalModuleHook = NormalModule.getCompilationHooks(compilation).loader;
  320. normalModuleHook.tap(`${MiniCssExtractPlugin.pluginName} loader`, (loaderContext, module) => {
  321. if (module.request === request) {
  322. // eslint-disable-next-line no-param-reassign
  323. module.loaders = loaders.map(loader => {
  324. return {
  325. type: null,
  326. loader: loader.path,
  327. options: loader.options,
  328. ident: loader.ident
  329. };
  330. });
  331. }
  332. });
  333. });
  334. /** @type {string | Buffer} */
  335. let source;
  336. childCompiler.hooks.compilation.tap(MiniCssExtractPlugin.pluginName,
  337. /**
  338. * @param {Compilation} compilation
  339. */
  340. compilation => {
  341. compilation.hooks.processAssets.tap(MiniCssExtractPlugin.pluginName, () => {
  342. source = compilation.assets[childFilename] && compilation.assets[childFilename].source();
  343. // Remove all chunk assets
  344. compilation.chunks.forEach(chunk => {
  345. chunk.files.forEach(file => {
  346. compilation.deleteAsset(file);
  347. });
  348. });
  349. });
  350. });
  351. childCompiler.runAsChild((error, entries, compilation) => {
  352. if (error) {
  353. callback(error);
  354. return;
  355. }
  356. if ( /** @type {Compilation} */compilation.errors.length > 0) {
  357. callback( /** @type {Compilation} */compilation.errors[0]);
  358. return;
  359. }
  360. /** @type {{ [name: string]: Source }} */
  361. const assets = Object.create(null);
  362. /** @type {Map<string, AssetInfo>} */
  363. const assetsInfo = new Map();
  364. for (const asset of /** @type {Compilation} */compilation.getAssets()) {
  365. assets[asset.name] = asset.source;
  366. assetsInfo.set(asset.name, asset.info);
  367. }
  368. /** @type {Compilation} */
  369. compilation.fileDependencies.forEach(dep => {
  370. this.addDependency(dep);
  371. }, this);
  372. /** @type {Compilation} */
  373. compilation.contextDependencies.forEach(dep => {
  374. this.addContextDependency(dep);
  375. }, this);
  376. if (!source) {
  377. callback(new Error("Didn't get a result from child compiler"));
  378. return;
  379. }
  380. let originalExports;
  381. try {
  382. originalExports = evalModuleCode(this, source, request);
  383. } catch (e) {
  384. callback( /** @type {Error} */e);
  385. return;
  386. }
  387. handleExports(originalExports, compilation, assets, assetsInfo);
  388. });
  389. }
  390. /**
  391. * @this {import("webpack").LoaderContext<LoaderOptions>}
  392. * @param {string} content
  393. */
  394. // eslint-disable-next-line consistent-return
  395. function loader(content) {
  396. if (this._compiler && this._compiler.options && this._compiler.options.experiments && this._compiler.options.experiments.css && this._module && (this._module.type === "css" || this._module.type === "css/auto" || this._module.type === "css/global" || this._module.type === "css/module")) {
  397. return content;
  398. }
  399. }
  400. module.exports = loader;
  401. module.exports.pitch = pitch;
  402. module.exports.hotLoader = hotLoader;