index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _webpack = _interopRequireDefault(require("webpack"));
  7. var _webpackSources = _interopRequireDefault(require("webpack-sources"));
  8. var _CssDependency = _interopRequireDefault(require("./CssDependency"));
  9. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  10. /* eslint-disable class-methods-use-this */
  11. const {
  12. ConcatSource,
  13. SourceMapSource,
  14. OriginalSource
  15. } = _webpackSources.default;
  16. const {
  17. Template,
  18. util: {
  19. createHash
  20. }
  21. } = _webpack.default;
  22. const MODULE_TYPE = 'css/mini-extract';
  23. const pluginName = 'mini-css-extract-plugin';
  24. const REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/i;
  25. const REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/i;
  26. const REGEXP_NAME = /\[name\]/i;
  27. const REGEXP_PLACEHOLDERS = /\[(name|id|chunkhash)\]/g;
  28. const DEFAULT_FILENAME = '[name].css';
  29. class CssDependencyTemplate {
  30. apply() {}
  31. }
  32. class CssModule extends _webpack.default.Module {
  33. constructor(dependency) {
  34. super(MODULE_TYPE, dependency.context);
  35. this.id = '';
  36. this._identifier = dependency.identifier;
  37. this._identifierIndex = dependency.identifierIndex;
  38. this.content = dependency.content;
  39. this.media = dependency.media;
  40. this.sourceMap = dependency.sourceMap;
  41. } // no source() so webpack doesn't do add stuff to the bundle
  42. size() {
  43. return this.content.length;
  44. }
  45. identifier() {
  46. return `css ${this._identifier} ${this._identifierIndex}`;
  47. }
  48. readableIdentifier(requestShortener) {
  49. return `css ${requestShortener.shorten(this._identifier)}${this._identifierIndex ? ` (${this._identifierIndex})` : ''}`;
  50. }
  51. nameForCondition() {
  52. const resource = this._identifier.split('!').pop();
  53. const idx = resource.indexOf('?');
  54. if (idx >= 0) {
  55. return resource.substring(0, idx);
  56. }
  57. return resource;
  58. }
  59. updateCacheModule(module) {
  60. this.content = module.content;
  61. this.media = module.media;
  62. this.sourceMap = module.sourceMap;
  63. }
  64. needRebuild() {
  65. return true;
  66. }
  67. build(options, compilation, resolver, fileSystem, callback) {
  68. this.buildInfo = {};
  69. this.buildMeta = {};
  70. callback();
  71. }
  72. updateHash(hash) {
  73. super.updateHash(hash);
  74. hash.update(this.content);
  75. hash.update(this.media || '');
  76. hash.update(this.sourceMap ? JSON.stringify(this.sourceMap) : '');
  77. }
  78. }
  79. class CssModuleFactory {
  80. create({
  81. dependencies: [dependency]
  82. }, callback) {
  83. callback(null, new CssModule(dependency));
  84. }
  85. }
  86. class MiniCssExtractPlugin {
  87. constructor(options = {}) {
  88. this.options = Object.assign({
  89. filename: DEFAULT_FILENAME,
  90. moduleFilename: () => this.options.filename || DEFAULT_FILENAME,
  91. ignoreOrder: false
  92. }, options);
  93. if (!this.options.chunkFilename) {
  94. const {
  95. filename
  96. } = this.options; // Anything changing depending on chunk is fine
  97. if (filename.match(REGEXP_PLACEHOLDERS)) {
  98. this.options.chunkFilename = filename;
  99. } else {
  100. // Elsewise prefix '[id].' in front of the basename to make it changing
  101. this.options.chunkFilename = filename.replace(/(^|\/)([^/]*(?:\?|$))/, '$1[id].$2');
  102. }
  103. }
  104. }
  105. apply(compiler) {
  106. compiler.hooks.thisCompilation.tap(pluginName, compilation => {
  107. compilation.dependencyFactories.set(_CssDependency.default, new CssModuleFactory());
  108. compilation.dependencyTemplates.set(_CssDependency.default, new CssDependencyTemplate());
  109. compilation.mainTemplate.hooks.renderManifest.tap(pluginName, (result, {
  110. chunk
  111. }) => {
  112. const renderedModules = Array.from(chunk.modulesIterable).filter(module => module.type === MODULE_TYPE);
  113. if (renderedModules.length > 0) {
  114. result.push({
  115. render: () => this.renderContentAsset(compilation, chunk, renderedModules, compilation.runtimeTemplate.requestShortener),
  116. filenameTemplate: ({
  117. chunk: chunkData
  118. }) => this.options.moduleFilename(chunkData),
  119. pathOptions: {
  120. chunk,
  121. contentHashType: MODULE_TYPE
  122. },
  123. identifier: `${pluginName}.${chunk.id}`,
  124. hash: chunk.contentHash[MODULE_TYPE]
  125. });
  126. }
  127. });
  128. compilation.chunkTemplate.hooks.renderManifest.tap(pluginName, (result, {
  129. chunk
  130. }) => {
  131. const renderedModules = Array.from(chunk.modulesIterable).filter(module => module.type === MODULE_TYPE);
  132. if (renderedModules.length > 0) {
  133. result.push({
  134. render: () => this.renderContentAsset(compilation, chunk, renderedModules, compilation.runtimeTemplate.requestShortener),
  135. filenameTemplate: this.options.chunkFilename,
  136. pathOptions: {
  137. chunk,
  138. contentHashType: MODULE_TYPE
  139. },
  140. identifier: `${pluginName}.${chunk.id}`,
  141. hash: chunk.contentHash[MODULE_TYPE]
  142. });
  143. }
  144. });
  145. compilation.mainTemplate.hooks.hashForChunk.tap(pluginName, (hash, chunk) => {
  146. const {
  147. chunkFilename
  148. } = this.options;
  149. if (REGEXP_CHUNKHASH.test(chunkFilename)) {
  150. hash.update(JSON.stringify(chunk.getChunkMaps(true).hash));
  151. }
  152. if (REGEXP_CONTENTHASH.test(chunkFilename)) {
  153. hash.update(JSON.stringify(chunk.getChunkMaps(true).contentHash[MODULE_TYPE] || {}));
  154. }
  155. if (REGEXP_NAME.test(chunkFilename)) {
  156. hash.update(JSON.stringify(chunk.getChunkMaps(true).name));
  157. }
  158. });
  159. compilation.hooks.contentHash.tap(pluginName, chunk => {
  160. const {
  161. outputOptions
  162. } = compilation;
  163. const {
  164. hashFunction,
  165. hashDigest,
  166. hashDigestLength
  167. } = outputOptions;
  168. const hash = createHash(hashFunction);
  169. for (const m of chunk.modulesIterable) {
  170. if (m.type === MODULE_TYPE) {
  171. m.updateHash(hash);
  172. }
  173. }
  174. const {
  175. contentHash
  176. } = chunk;
  177. contentHash[MODULE_TYPE] = hash.digest(hashDigest).substring(0, hashDigestLength);
  178. });
  179. const {
  180. mainTemplate
  181. } = compilation;
  182. mainTemplate.hooks.localVars.tap(pluginName, (source, chunk) => {
  183. const chunkMap = this.getCssChunkObject(chunk);
  184. if (Object.keys(chunkMap).length > 0) {
  185. return Template.asString([source, '', '// object to store loaded CSS chunks', 'var installedCssChunks = {', Template.indent(chunk.ids.map(id => `${JSON.stringify(id)}: 0`).join(',\n')), '}']);
  186. }
  187. return source;
  188. });
  189. mainTemplate.hooks.requireEnsure.tap(pluginName, (source, chunk, hash) => {
  190. const chunkMap = this.getCssChunkObject(chunk);
  191. if (Object.keys(chunkMap).length > 0) {
  192. const chunkMaps = chunk.getChunkMaps();
  193. const {
  194. crossOriginLoading
  195. } = mainTemplate.outputOptions;
  196. const linkHrefPath = mainTemplate.getAssetPath(JSON.stringify(this.options.chunkFilename), {
  197. hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`,
  198. hashWithLength: length => `" + ${mainTemplate.renderCurrentHashCode(hash, length)} + "`,
  199. chunk: {
  200. id: '" + chunkId + "',
  201. hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`,
  202. hashWithLength(length) {
  203. const shortChunkHashMap = Object.create(null);
  204. for (const chunkId of Object.keys(chunkMaps.hash)) {
  205. if (typeof chunkMaps.hash[chunkId] === 'string') {
  206. shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substring(0, length);
  207. }
  208. }
  209. return `" + ${JSON.stringify(shortChunkHashMap)}[chunkId] + "`;
  210. },
  211. contentHash: {
  212. [MODULE_TYPE]: `" + ${JSON.stringify(chunkMaps.contentHash[MODULE_TYPE])}[chunkId] + "`
  213. },
  214. contentHashWithLength: {
  215. [MODULE_TYPE]: length => {
  216. const shortContentHashMap = {};
  217. const contentHash = chunkMaps.contentHash[MODULE_TYPE];
  218. for (const chunkId of Object.keys(contentHash)) {
  219. if (typeof contentHash[chunkId] === 'string') {
  220. shortContentHashMap[chunkId] = contentHash[chunkId].substring(0, length);
  221. }
  222. }
  223. return `" + ${JSON.stringify(shortContentHashMap)}[chunkId] + "`;
  224. }
  225. },
  226. name: `" + (${JSON.stringify(chunkMaps.name)}[chunkId]||chunkId) + "`
  227. },
  228. contentHashType: MODULE_TYPE
  229. });
  230. return Template.asString([source, '', `// ${pluginName} CSS loading`, `var cssChunks = ${JSON.stringify(chunkMap)};`, 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', Template.indent(['promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) {', Template.indent([`var href = ${linkHrefPath};`, `var fullhref = ${mainTemplate.requireFn}.p + href;`, 'var existingLinkTags = document.getElementsByTagName("link");', 'for(var i = 0; i < existingLinkTags.length; i++) {', Template.indent(['var tag = existingLinkTags[i];', 'var dataHref = tag.getAttribute("data-href") || tag.getAttribute("href");', 'if(tag.rel === "stylesheet" && (dataHref === href || dataHref === fullhref)) return resolve();']), '}', 'var existingStyleTags = document.getElementsByTagName("style");', 'for(var i = 0; i < existingStyleTags.length; i++) {', Template.indent(['var tag = existingStyleTags[i];', 'var dataHref = tag.getAttribute("data-href");', 'if(dataHref === href || dataHref === fullhref) return resolve();']), '}', 'var linkTag = document.createElement("link");', 'linkTag.rel = "stylesheet";', 'linkTag.type = "text/css";', 'linkTag.onload = resolve;', 'linkTag.onerror = function(event) {', Template.indent(['var request = event && event.target && event.target.src || fullhref;', 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + request + ")");', 'err.code = "CSS_CHUNK_LOAD_FAILED";', 'err.request = request;', 'delete installedCssChunks[chunkId]', 'linkTag.parentNode.removeChild(linkTag)', 'reject(err);']), '};', 'linkTag.href = fullhref;', crossOriginLoading ? Template.asString([`if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, Template.indent(`linkTag.crossOrigin = ${JSON.stringify(crossOriginLoading)};`), '}']) : '', 'var head = document.getElementsByTagName("head")[0];', 'head.appendChild(linkTag);']), '}).then(function() {', Template.indent(['installedCssChunks[chunkId] = 0;']), '}));']), '}']);
  231. }
  232. return source;
  233. });
  234. });
  235. }
  236. getCssChunkObject(mainChunk) {
  237. const obj = {};
  238. for (const chunk of mainChunk.getAllAsyncChunks()) {
  239. for (const module of chunk.modulesIterable) {
  240. if (module.type === MODULE_TYPE) {
  241. obj[chunk.id] = 1;
  242. break;
  243. }
  244. }
  245. }
  246. return obj;
  247. }
  248. renderContentAsset(compilation, chunk, modules, requestShortener) {
  249. let usedModules;
  250. const [chunkGroup] = chunk.groupsIterable;
  251. if (typeof chunkGroup.getModuleIndex2 === 'function') {
  252. // Store dependencies for modules
  253. const moduleDependencies = new Map(modules.map(m => [m, new Set()]));
  254. const moduleDependenciesReasons = new Map(modules.map(m => [m, new Map()])); // Get ordered list of modules per chunk group
  255. // This loop also gathers dependencies from the ordered lists
  256. // Lists are in reverse order to allow to use Array.pop()
  257. const modulesByChunkGroup = Array.from(chunk.groupsIterable, cg => {
  258. const sortedModules = modules.map(m => {
  259. return {
  260. module: m,
  261. index: cg.getModuleIndex2(m)
  262. };
  263. }) // eslint-disable-next-line no-undefined
  264. .filter(item => item.index !== undefined).sort((a, b) => b.index - a.index).map(item => item.module);
  265. for (let i = 0; i < sortedModules.length; i++) {
  266. const set = moduleDependencies.get(sortedModules[i]);
  267. const reasons = moduleDependenciesReasons.get(sortedModules[i]);
  268. for (let j = i + 1; j < sortedModules.length; j++) {
  269. const module = sortedModules[j];
  270. set.add(module);
  271. const reason = reasons.get(module) || new Set();
  272. reason.add(cg);
  273. reasons.set(module, reason);
  274. }
  275. }
  276. return sortedModules;
  277. }); // set with already included modules in correct order
  278. usedModules = new Set();
  279. const unusedModulesFilter = m => !usedModules.has(m);
  280. while (usedModules.size < modules.length) {
  281. let success = false;
  282. let bestMatch;
  283. let bestMatchDeps; // get first module where dependencies are fulfilled
  284. for (const list of modulesByChunkGroup) {
  285. // skip and remove already added modules
  286. while (list.length > 0 && usedModules.has(list[list.length - 1])) {
  287. list.pop();
  288. } // skip empty lists
  289. if (list.length !== 0) {
  290. const module = list[list.length - 1];
  291. const deps = moduleDependencies.get(module); // determine dependencies that are not yet included
  292. const failedDeps = Array.from(deps).filter(unusedModulesFilter); // store best match for fallback behavior
  293. if (!bestMatchDeps || bestMatchDeps.length > failedDeps.length) {
  294. bestMatch = list;
  295. bestMatchDeps = failedDeps;
  296. }
  297. if (failedDeps.length === 0) {
  298. // use this module and remove it from list
  299. usedModules.add(list.pop());
  300. success = true;
  301. break;
  302. }
  303. }
  304. }
  305. if (!success) {
  306. // no module found => there is a conflict
  307. // use list with fewest failed deps
  308. // and emit a warning
  309. const fallbackModule = bestMatch.pop();
  310. if (!this.options.ignoreOrder) {
  311. const reasons = moduleDependenciesReasons.get(fallbackModule);
  312. compilation.warnings.push(new Error([`chunk ${chunk.name || chunk.id} [${pluginName}]`, 'Conflicting order. Following module has been added:', ` * ${fallbackModule.readableIdentifier(requestShortener)}`, 'despite it was not able to fulfill desired ordering with these modules:', ...bestMatchDeps.map(m => {
  313. const goodReasonsMap = moduleDependenciesReasons.get(m);
  314. const goodReasons = goodReasonsMap && goodReasonsMap.get(fallbackModule);
  315. const failedChunkGroups = Array.from(reasons.get(m), cg => cg.name).join(', ');
  316. const goodChunkGroups = goodReasons && Array.from(goodReasons, cg => cg.name).join(', ');
  317. return [` * ${m.readableIdentifier(requestShortener)}`, ` - couldn't fulfill desired order of chunk group(s) ${failedChunkGroups}`, goodChunkGroups && ` - while fulfilling desired order of chunk group(s) ${goodChunkGroups}`].filter(Boolean).join('\n');
  318. })].join('\n')));
  319. }
  320. usedModules.add(fallbackModule);
  321. }
  322. }
  323. } else {
  324. // fallback for older webpack versions
  325. // (to avoid a breaking change)
  326. // TODO remove this in next major version
  327. // and increase minimum webpack version to 4.12.0
  328. modules.sort((a, b) => a.index2 - b.index2);
  329. usedModules = modules;
  330. }
  331. const source = new ConcatSource();
  332. const externalsSource = new ConcatSource();
  333. for (const m of usedModules) {
  334. if (/^@import url/.test(m.content)) {
  335. // HACK for IE
  336. // http://stackoverflow.com/a/14676665/1458162
  337. let {
  338. content
  339. } = m;
  340. if (m.media) {
  341. // insert media into the @import
  342. // this is rar
  343. // TODO improve this and parse the CSS to support multiple medias
  344. content = content.replace(/;|\s*$/, m.media);
  345. }
  346. externalsSource.add(content);
  347. externalsSource.add('\n');
  348. } else {
  349. if (m.media) {
  350. source.add(`@media ${m.media} {\n`);
  351. }
  352. if (m.sourceMap) {
  353. source.add(new SourceMapSource(m.content, m.readableIdentifier(requestShortener), m.sourceMap));
  354. } else {
  355. source.add(new OriginalSource(m.content, m.readableIdentifier(requestShortener)));
  356. }
  357. source.add('\n');
  358. if (m.media) {
  359. source.add('}\n');
  360. }
  361. }
  362. }
  363. return new ConcatSource(externalsSource, source);
  364. }
  365. }
  366. MiniCssExtractPlugin.loader = require.resolve('./loader');
  367. var _default = MiniCssExtractPlugin;
  368. exports.default = _default;