You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 16 KiB

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