loader.js 13 KB

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