loader.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 accept = context.locals ? "" : "module.hot.accept(undefined, cssReload);";
  43. return `${content}
  44. if(module.hot) {
  45. // ${Date.now()}
  46. var cssReload = require(${stringifyRequest(context.loaderContext, path.join(__dirname, "hmr/hotModuleReplacement.js"))})(module.id, ${JSON.stringify({
  47. ...context.options,
  48. locals: !!context.locals
  49. })});
  50. module.hot.dispose(cssReload);
  51. ${accept}
  52. }
  53. `;
  54. }
  55. /**
  56. * @this {import("webpack").LoaderContext<LoaderOptions>}
  57. * @param {string} request
  58. */
  59. function pitch(request) {
  60. // @ts-ignore
  61. const options = this.getOptions( /** @type {Schema} */schema);
  62. const emit = typeof options.emit !== "undefined" ? options.emit : true;
  63. const callback = this.async();
  64. const optionsFromPlugin = /** @type {TODO} */this[MiniCssExtractPlugin.pluginSymbol];
  65. if (!optionsFromPlugin) {
  66. 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"));
  67. return;
  68. }
  69. const {
  70. webpack
  71. } = /** @type {Compiler} */this._compiler;
  72. /**
  73. * @param {TODO} originalExports
  74. * @param {Compilation} [compilation]
  75. * @param {{ [name: string]: Source }} [assets]
  76. * @param {Map<string, AssetInfo>} [assetsInfo]
  77. * @returns {void}
  78. */
  79. const handleExports = (originalExports, compilation, assets, assetsInfo) => {
  80. /** @type {Locals | undefined} */
  81. let locals;
  82. let namedExport;
  83. const esModule = typeof options.esModule !== "undefined" ? options.esModule : true;
  84. /**
  85. * @param {Dependency[] | [null, object][]} dependencies
  86. */
  87. const addDependencies = dependencies => {
  88. if (!Array.isArray(dependencies) && dependencies != null) {
  89. throw new Error(`Exported value was not extracted as an array: ${JSON.stringify(dependencies)}`);
  90. }
  91. const identifierCountMap = new Map();
  92. let lastDep;
  93. for (const dependency of dependencies) {
  94. if (! /** @type {Dependency} */dependency.identifier || !emit) {
  95. // eslint-disable-next-line no-continue
  96. continue;
  97. }
  98. const count = identifierCountMap.get( /** @type {Dependency} */dependency.identifier) || 0;
  99. const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack);
  100. /** @type {NormalModule} */
  101. this._module.addDependency(lastDep = new CssDependency( /** @type {Dependency} */
  102. dependency, /** @type {Dependency} */
  103. dependency.context, count));
  104. identifierCountMap.set( /** @type {Dependency} */
  105. dependency.identifier, count + 1);
  106. }
  107. if (lastDep && assets) {
  108. lastDep.assets = assets;
  109. lastDep.assetsInfo = assetsInfo;
  110. }
  111. };
  112. try {
  113. // eslint-disable-next-line no-underscore-dangle
  114. const exports = originalExports.__esModule ? originalExports.default : originalExports;
  115. namedExport =
  116. // eslint-disable-next-line no-underscore-dangle
  117. originalExports.__esModule && (!originalExports.default || !("locals" in originalExports.default));
  118. if (namedExport) {
  119. Object.keys(originalExports).forEach(key => {
  120. if (key !== "default") {
  121. if (!locals) {
  122. locals = {};
  123. }
  124. /** @type {Locals} */
  125. locals[key] = originalExports[key];
  126. }
  127. });
  128. } else {
  129. locals = exports && exports.locals;
  130. }
  131. /** @type {Dependency[] | [null, object][]} */
  132. let dependencies;
  133. if (!Array.isArray(exports)) {
  134. dependencies = [[null, exports]];
  135. } else {
  136. dependencies = exports.map(([id, content, media, sourceMap, supports, layer]) => {
  137. let identifier = id;
  138. let context;
  139. if (compilation) {
  140. const module = /** @type {Module} */
  141. findModuleById(compilation, id);
  142. identifier = module.identifier();
  143. ({
  144. context
  145. } = module);
  146. } else {
  147. // TODO check if this context is used somewhere
  148. context = this.rootContext;
  149. }
  150. return {
  151. identifier,
  152. context,
  153. content: Buffer.from(content),
  154. media,
  155. supports,
  156. layer,
  157. sourceMap: sourceMap ? Buffer.from(JSON.stringify(sourceMap)) :
  158. // eslint-disable-next-line no-undefined
  159. undefined
  160. };
  161. });
  162. }
  163. addDependencies(dependencies);
  164. } catch (e) {
  165. callback( /** @type {Error} */e);
  166. return;
  167. }
  168. const result = locals ? namedExport ? Object.keys(locals).map(key => `\nexport var ${key} = ${stringifyLocal( /** @type {Locals} */locals[key])};`).join("") : `\n${esModule ? "export default" : "module.exports ="} ${JSON.stringify(locals)};` : esModule ? `\nexport {};` : "";
  169. let resultSource = `// extracted by ${MiniCssExtractPlugin.pluginName}`;
  170. // only attempt hotreloading if the css is actually used for something other than hash values
  171. resultSource += this.hot && emit ? hotLoader(result, {
  172. loaderContext: this,
  173. options,
  174. locals
  175. }) : result;
  176. callback(null, resultSource);
  177. };
  178. let {
  179. publicPath
  180. } = /** @type {Compilation} */
  181. this._compilation.outputOptions;
  182. if (typeof options.publicPath === "string") {
  183. // eslint-disable-next-line prefer-destructuring
  184. publicPath = options.publicPath;
  185. } else if (typeof options.publicPath === "function") {
  186. publicPath = options.publicPath(this.resourcePath, this.rootContext);
  187. }
  188. if (publicPath === "auto") {
  189. publicPath = AUTO_PUBLIC_PATH;
  190. }
  191. if (typeof optionsFromPlugin.experimentalUseImportModule === "undefined" && typeof this.importModule === "function" || optionsFromPlugin.experimentalUseImportModule) {
  192. if (!this.importModule) {
  193. 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."));
  194. return;
  195. }
  196. let publicPathForExtract;
  197. if (typeof publicPath === "string") {
  198. const isAbsolutePublicPath = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/.test(publicPath);
  199. publicPathForExtract = isAbsolutePublicPath ? publicPath : `${ABSOLUTE_PUBLIC_PATH}${publicPath.replace(/\./g, SINGLE_DOT_PATH_SEGMENT)}`;
  200. } else {
  201. publicPathForExtract = publicPath;
  202. }
  203. this.importModule(`${this.resourcePath}.webpack[javascript/auto]!=!!!${request}`, {
  204. layer: options.layer,
  205. publicPath: /** @type {string} */publicPathForExtract,
  206. baseUri: `${BASE_URI}/`
  207. },
  208. /**
  209. * @param {Error | null | undefined} error
  210. * @param {object} exports
  211. */
  212. (error, exports) => {
  213. if (error) {
  214. callback(error);
  215. return;
  216. }
  217. handleExports(exports);
  218. });
  219. return;
  220. }
  221. const loaders = this.loaders.slice(this.loaderIndex + 1);
  222. this.addDependency(this.resourcePath);
  223. const childFilename = "*";
  224. const outputOptions = {
  225. filename: childFilename,
  226. publicPath
  227. };
  228. const childCompiler = /** @type {Compilation} */
  229. this._compilation.createChildCompiler(`${MiniCssExtractPlugin.pluginName} ${request}`, outputOptions);
  230. // The templates are compiled and executed by NodeJS - similar to server side rendering
  231. // Unfortunately this causes issues as some loaders require an absolute URL to support ES Modules
  232. // The following config enables relative URL support for the child compiler
  233. childCompiler.options.module = {
  234. ...childCompiler.options.module
  235. };
  236. childCompiler.options.module.parser = {
  237. ...childCompiler.options.module.parser
  238. };
  239. childCompiler.options.module.parser.javascript = {
  240. ...childCompiler.options.module.parser.javascript,
  241. url: "relative"
  242. };
  243. const {
  244. NodeTemplatePlugin
  245. } = webpack.node;
  246. const {
  247. NodeTargetPlugin
  248. } = webpack.node;
  249. new NodeTemplatePlugin(outputOptions).apply(childCompiler);
  250. new NodeTargetPlugin().apply(childCompiler);
  251. const {
  252. EntryOptionPlugin
  253. } = webpack;
  254. const {
  255. library: {
  256. EnableLibraryPlugin
  257. }
  258. } = webpack;
  259. new EnableLibraryPlugin("commonjs2").apply(childCompiler);
  260. EntryOptionPlugin.applyEntryOption(childCompiler, this.context, {
  261. child: {
  262. library: {
  263. type: "commonjs2"
  264. },
  265. import: [`!!${request}`]
  266. }
  267. });
  268. const {
  269. LimitChunkCountPlugin
  270. } = webpack.optimize;
  271. new LimitChunkCountPlugin({
  272. maxChunks: 1
  273. }).apply(childCompiler);
  274. const {
  275. NormalModule
  276. } = webpack;
  277. childCompiler.hooks.thisCompilation.tap(`${MiniCssExtractPlugin.pluginName} loader`,
  278. /**
  279. * @param {Compilation} compilation
  280. */
  281. compilation => {
  282. const normalModuleHook = NormalModule.getCompilationHooks(compilation).loader;
  283. normalModuleHook.tap(`${MiniCssExtractPlugin.pluginName} loader`, (loaderContext, module) => {
  284. if (module.request === request) {
  285. // eslint-disable-next-line no-param-reassign
  286. module.loaders = loaders.map(loader => {
  287. return {
  288. type: null,
  289. loader: loader.path,
  290. options: loader.options,
  291. ident: loader.ident
  292. };
  293. });
  294. }
  295. });
  296. });
  297. /** @type {string | Buffer} */
  298. let source;
  299. childCompiler.hooks.compilation.tap(MiniCssExtractPlugin.pluginName,
  300. /**
  301. * @param {Compilation} compilation
  302. */
  303. compilation => {
  304. compilation.hooks.processAssets.tap(MiniCssExtractPlugin.pluginName, () => {
  305. source = compilation.assets[childFilename] && compilation.assets[childFilename].source();
  306. // Remove all chunk assets
  307. compilation.chunks.forEach(chunk => {
  308. chunk.files.forEach(file => {
  309. compilation.deleteAsset(file);
  310. });
  311. });
  312. });
  313. });
  314. childCompiler.runAsChild((error, entries, compilation) => {
  315. if (error) {
  316. callback(error);
  317. return;
  318. }
  319. if ( /** @type {Compilation} */compilation.errors.length > 0) {
  320. callback( /** @type {Compilation} */compilation.errors[0]);
  321. return;
  322. }
  323. /** @type {{ [name: string]: Source }} */
  324. const assets = Object.create(null);
  325. /** @type {Map<string, AssetInfo>} */
  326. const assetsInfo = new Map();
  327. for (const asset of /** @type {Compilation} */compilation.getAssets()) {
  328. assets[asset.name] = asset.source;
  329. assetsInfo.set(asset.name, asset.info);
  330. }
  331. /** @type {Compilation} */
  332. compilation.fileDependencies.forEach(dep => {
  333. this.addDependency(dep);
  334. }, this);
  335. /** @type {Compilation} */
  336. compilation.contextDependencies.forEach(dep => {
  337. this.addContextDependency(dep);
  338. }, this);
  339. if (!source) {
  340. callback(new Error("Didn't get a result from child compiler"));
  341. return;
  342. }
  343. let originalExports;
  344. try {
  345. originalExports = evalModuleCode(this, source, request);
  346. } catch (e) {
  347. callback( /** @type {Error} */e);
  348. return;
  349. }
  350. handleExports(originalExports, compilation, assets, assetsInfo);
  351. });
  352. }
  353. module.exports = {
  354. default: function loader() {},
  355. pitch
  356. };