diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index a3f31c9b..1053483a 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -56,7 +56,7 @@ jobs: matrix: os: [ubuntu-latest, windows-latest, macos-latest] node-version: [10.x, 12.x, 14.x] - webpack-version: [4, latest] + webpack-version: [latest] runs-on: ${{ matrix.os }} diff --git a/jest.config.js b/jest.config.js index 0cff348b..9d9cc847 100644 --- a/jest.config.js +++ b/jest.config.js @@ -3,5 +3,4 @@ module.exports = { transformIgnorePatterns: ['/node_modules/', '/dist/'], watchPathIgnorePatterns: ['/test/js'], setupFilesAfterEnv: ['/setupTest.js'], - snapshotResolver: './test/helpers/snapshotResolver.js', }; diff --git a/package-lock.json b/package-lock.json index 2558dec5..7067dafe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,6 +5,7 @@ "requires": true, "packages": { "": { + "name": "mini-css-extract-plugin", "version": "1.6.0", "license": "MIT", "dependencies": { @@ -51,7 +52,7 @@ "url": "https://opencollective.com/webpack" }, "peerDependencies": { - "webpack": "^4.4.0 || ^5.0.0" + "webpack": "^5.0.0" } }, "node_modules/@babel/cli": { diff --git a/package.json b/package.json index 404527e9..6cc59a27 100644 --- a/package.json +++ b/package.json @@ -39,7 +39,7 @@ "dist" ], "peerDependencies": { - "webpack": "^4.4.0 || ^5.0.0" + "webpack": "^5.0.0" }, "dependencies": { "loader-utils": "^2.0.0", diff --git a/src/index.js b/src/index.js index 4c1b009a..91bafed3 100644 --- a/src/index.js +++ b/src/index.js @@ -2,17 +2,19 @@ import { validate } from 'schema-utils'; +import { getUndoPath } from 'webpack/lib/util/identifier'; + import schema from './plugin-options.json'; -import { MODULE_TYPE, compareModulesByIdentifier } from './utils'; +import { + MODULE_TYPE, + AUTO_PUBLIC_PATH, + compareModulesByIdentifier, +} from './utils'; export const pluginName = 'mini-css-extract-plugin'; export const pluginSymbol = Symbol(pluginName); -const REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/i; -const REGEXP_CONTENTHASH = /\[contenthash(?::(\d+))?\]/i; -const REGEXP_NAME = /\[name\]/i; const DEFAULT_FILENAME = '[name].css'; - const TYPES = new Set([MODULE_TYPE]); const CODE_GENERATION_RESULT = { sources: new Map(), @@ -152,48 +154,42 @@ class MiniCssExtractPlugin { cssModuleCache.set(webpack, CssModule); - if ( - webpack.util && - webpack.util.serialization && - webpack.util.serialization.register - ) { - webpack.util.serialization.register( - CssModule, - 'mini-css-extract-plugin/dist/CssModule', - null, - { - serialize(instance, context) { - instance.serialize(context); - }, - deserialize(context) { - const { read } = context; - - const contextModule = read(); - const identifier = read(); - const identifierIndex = read(); - const content = read(); - const media = read(); - const sourceMap = read(); - const { assets, assetsInfo } = read(); - - const dep = new CssModule({ - context: contextModule, - identifier, - identifierIndex, - content, - media, - sourceMap, - assets, - assetsInfo, - }); - - dep.deserialize(context); - - return dep; - }, - } - ); - } + webpack.util.serialization.register( + CssModule, + 'mini-css-extract-plugin/dist/CssModule', + null, + { + serialize(instance, context) { + instance.serialize(context); + }, + deserialize(context) { + const { read } = context; + + const contextModule = read(); + const identifier = read(); + const identifierIndex = read(); + const content = read(); + const media = read(); + const sourceMap = read(); + const { assets, assetsInfo } = read(); + + const dep = new CssModule({ + context: contextModule, + identifier, + identifierIndex, + content, + media, + sourceMap, + assets, + assetsInfo, + }); + + dep.deserialize(context); + + return dep; + }, + } + ); return CssModule; } @@ -257,45 +253,39 @@ class MiniCssExtractPlugin { cssDependencyCache.set(webpack, CssDependency); - if ( - webpack.util && - webpack.util.serialization && - webpack.util.serialization.register - ) { - webpack.util.serialization.register( - CssDependency, - 'mini-css-extract-plugin/dist/CssDependency', - null, - { - serialize(instance, context) { - instance.serialize(context); - }, - deserialize(context) { - const { read } = context; - const dep = new CssDependency( - { - identifier: read(), - content: read(), - media: read(), - sourceMap: read(), - }, - read(), - read() - ); - - const assets = read(); - const assetsInfo = read(); - - dep.assets = assets; - dep.assetsInfo = assetsInfo; - - dep.deserialize(context); - - return dep; - }, - } - ); - } + webpack.util.serialization.register( + CssDependency, + 'mini-css-extract-plugin/dist/CssDependency', + null, + { + serialize(instance, context) { + instance.serialize(context); + }, + deserialize(context) { + const { read } = context; + const dep = new CssDependency( + { + identifier: read(), + content: read(), + media: read(), + sourceMap: read(), + }, + read(), + read() + ); + + const assets = read(); + const assetsInfo = read(); + + dep.assets = assets; + dep.assetsInfo = assetsInfo; + + dep.deserialize(context); + + return dep; + }, + } + ); return CssDependency; } @@ -354,10 +344,7 @@ class MiniCssExtractPlugin { /** @param {import("webpack").Compiler} compiler */ apply(compiler) { - const webpack = compiler.webpack - ? compiler.webpack - : // eslint-disable-next-line global-require - require('webpack'); + const { webpack } = compiler; if (this.options.experimentalUseImportModule) { if (!compiler.options.experiments) { @@ -373,45 +360,27 @@ class MiniCssExtractPlugin { // TODO bug in webpack, remove it after it will be fixed // webpack tries to `require` loader firstly when serializer doesn't found - if ( - webpack.util && - webpack.util.serialization && - webpack.util.serialization.registerLoader - ) { - webpack.util.serialization.registerLoader( - /^mini-css-extract-plugin\//, - () => true - ); - } - - const isWebpack4 = compiler.webpack - ? false - : typeof compiler.resolvers !== 'undefined'; + webpack.util.serialization.registerLoader( + /^mini-css-extract-plugin\//, + () => true + ); - if (!isWebpack4) { - const { splitChunks } = compiler.options.optimization; + const { splitChunks } = compiler.options.optimization; - if (splitChunks) { - if (splitChunks.defaultSizeTypes.includes('...')) { - splitChunks.defaultSizeTypes.push(MODULE_TYPE); - } + if (splitChunks) { + if (splitChunks.defaultSizeTypes.includes('...')) { + splitChunks.defaultSizeTypes.push(MODULE_TYPE); } } const CssModule = MiniCssExtractPlugin.getCssModule(webpack); const CssDependency = MiniCssExtractPlugin.getCssDependency(webpack); - const NormalModule = - compiler.webpack && compiler.webpack.NormalModule - ? compiler.webpack.NormalModule - : // eslint-disable-next-line global-require - require('webpack/lib/NormalModule'); + const { NormalModule } = compiler.webpack; compiler.hooks.compilation.tap(pluginName, (compilation) => { - const normalModuleHook = - typeof NormalModule.getCompilationHooks !== 'undefined' - ? NormalModule.getCompilationHooks(compilation).loader - : compilation.hooks.normalModuleLoader; + const { loader: normalModuleHook } = + NormalModule.getCompilationHooks(compilation); normalModuleHook.tap(pluginName, (loaderContext) => { // eslint-disable-next-line no-param-reassign @@ -444,168 +413,62 @@ class MiniCssExtractPlugin { new CssDependencyTemplate() ); - if (isWebpack4) { - compilation.mainTemplate.hooks.renderManifest.tap( - pluginName, - (result, { chunk }) => { - const { chunkGraph } = compilation; - - const renderedModules = Array.from( - this.getChunkModules(chunk, chunkGraph) - ).filter((module) => module.type === MODULE_TYPE); - - const filenameTemplate = - chunk.filenameTemplate || this.options.filename; - - if (renderedModules.length > 0) { - result.push({ - render: () => - this.renderContentAsset( - compiler, - compilation, - chunk, - renderedModules, - compilation.runtimeTemplate.requestShortener - ), - filenameTemplate, - pathOptions: { - chunk, - contentHashType: MODULE_TYPE, - }, - identifier: `${pluginName}.${chunk.id}`, - hash: chunk.contentHash[MODULE_TYPE], - }); - } - } - ); - - compilation.chunkTemplate.hooks.renderManifest.tap( - pluginName, - (result, { chunk }) => { - const { chunkGraph } = compilation; - - const renderedModules = Array.from( - this.getChunkModules(chunk, chunkGraph) - ).filter((module) => module.type === MODULE_TYPE); - - const filenameTemplate = - chunk.filenameTemplate || this.options.chunkFilename; - - if (renderedModules.length > 0) { - result.push({ - render: () => - this.renderContentAsset( - compiler, - compilation, - chunk, - renderedModules, - compilation.runtimeTemplate.requestShortener - ), - filenameTemplate, - pathOptions: { - chunk, - contentHashType: MODULE_TYPE, - }, - identifier: `${pluginName}.${chunk.id}`, - hash: chunk.contentHash[MODULE_TYPE], - }); - } - } - ); - } else { - compilation.hooks.renderManifest.tap( - pluginName, - (result, { chunk }) => { - const { chunkGraph } = compilation; - const { HotUpdateChunk } = webpack; - - // We don't need hot update chunks for css - // We will use the real asset instead to update - if (chunk instanceof HotUpdateChunk) { - return; - } + compilation.hooks.renderManifest.tap(pluginName, (result, { chunk }) => { + const { chunkGraph } = compilation; + const { HotUpdateChunk } = webpack; - const renderedModules = Array.from( - this.getChunkModules(chunk, chunkGraph) - ).filter((module) => module.type === MODULE_TYPE); - - const filenameTemplate = chunk.canBeInitial() - ? this.options.filename - : this.options.chunkFilename; - - if (renderedModules.length > 0) { - result.push({ - render: () => - this.renderContentAsset( - compiler, - compilation, - chunk, - renderedModules, - compilation.runtimeTemplate.requestShortener - ), - filenameTemplate, - pathOptions: { - chunk, - contentHashType: MODULE_TYPE, - }, - identifier: `${pluginName}.${chunk.id}`, - hash: chunk.contentHash[MODULE_TYPE], - }); - } - } - ); - } + // We don't need hot update chunks for css + // We will use the real asset instead to update + if (chunk instanceof HotUpdateChunk) { + return; + } - /* - * For webpack 5 this will be unneeded once the logic uses a RuntimeModule - * as the content of runtime modules is hashed and added to the chunk hash automatically - * */ - if (isWebpack4) { - compilation.mainTemplate.hooks.hashForChunk.tap( - pluginName, - (hash, chunk) => { - const { chunkFilename } = this.options; - - if (REGEXP_CHUNKHASH.test(chunkFilename)) { - hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); - } + const renderedModules = Array.from( + this.getChunkModules(chunk, chunkGraph) + ).filter((module) => module.type === MODULE_TYPE); - if (REGEXP_CONTENTHASH.test(chunkFilename)) { - hash.update( - JSON.stringify( - chunk.getChunkMaps(true).contentHash[MODULE_TYPE] || {} - ) - ); - } + const filenameTemplate = chunk.canBeInitial() + ? this.options.filename + : this.options.chunkFilename; - if (REGEXP_NAME.test(chunkFilename)) { - hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); - } - } - ); - } + if (renderedModules.length > 0) { + result.push({ + render: () => + this.renderContentAsset( + compiler, + compilation, + chunk, + renderedModules, + compilation.runtimeTemplate.requestShortener, + filenameTemplate, + { + contentHashType: MODULE_TYPE, + chunk, + } + ), + filenameTemplate, + pathOptions: { + chunk, + contentHashType: MODULE_TYPE, + }, + identifier: `${pluginName}.${chunk.id}`, + hash: chunk.contentHash[MODULE_TYPE], + }); + } + }); compilation.hooks.contentHash.tap(pluginName, (chunk) => { const { outputOptions, chunkGraph } = compilation; - const modules = isWebpack4 - ? Array.from(this.getChunkModules(chunk, chunkGraph)).filter( - (module) => module.type === MODULE_TYPE - ) - : this.sortModules( - compilation, - chunk, - chunkGraph.getChunkModulesIterableBySourceType( - chunk, - MODULE_TYPE - ), - compilation.runtimeTemplate.requestShortener - ); + const modules = this.sortModules( + compilation, + chunk, + chunkGraph.getChunkModulesIterableBySourceType(chunk, MODULE_TYPE), + compilation.runtimeTemplate.requestShortener + ); if (modules) { const { hashFunction, hashDigest, hashDigestLength } = outputOptions; - const createHash = compiler.webpack - ? compiler.webpack.util.createHash - : webpack.util.createHash; + const { createHash } = compiler.webpack.util; const hash = createHash(hashFunction); for (const m of modules) { @@ -620,498 +483,300 @@ class MiniCssExtractPlugin { }); const { Template } = webpack; - const { mainTemplate } = compilation; - - if (isWebpack4) { - mainTemplate.hooks.localVars.tap(pluginName, (source, chunk) => { - const chunkMap = this.getCssChunkObject(chunk, compilation); - - if (Object.keys(chunkMap).length > 0) { - return Template.asString([ - source, - '', - '// object to store loaded CSS chunks', - 'var installedCssChunks = {', - Template.indent( - chunk.ids.map((id) => `${JSON.stringify(id)}: 0`).join(',\n') - ), - '};', - ]); - } - return source; - }); + const { RuntimeGlobals, runtime } = webpack; - mainTemplate.hooks.requireEnsure.tap( - pluginName, - (source, chunk, hash) => { - const chunkMap = this.getCssChunkObject(chunk, compilation); + // eslint-disable-next-line no-shadow + const getCssChunkObject = (mainChunk, compilation) => { + const obj = {}; + const { chunkGraph } = compilation; - if (Object.keys(chunkMap).length > 0) { - const chunkMaps = chunk.getChunkMaps(); - const { crossOriginLoading } = mainTemplate.outputOptions; - const linkHrefPath = mainTemplate.getAssetPath( - JSON.stringify(this.options.chunkFilename), - { - hash: `" + ${mainTemplate.renderCurrentHashCode(hash)} + "`, - hashWithLength: (length) => - `" + ${mainTemplate.renderCurrentHashCode( - hash, - length - )} + "`, - chunk: { - id: '" + chunkId + "', - hash: `" + ${JSON.stringify(chunkMaps.hash)}[chunkId] + "`, - hashWithLength(length) { - const shortChunkHashMap = Object.create(null); - - for (const chunkId of Object.keys(chunkMaps.hash)) { - if (typeof chunkMaps.hash[chunkId] === 'string') { - shortChunkHashMap[chunkId] = chunkMaps.hash[ - chunkId - ].substring(0, length); - } - } - - return `" + ${JSON.stringify( - shortChunkHashMap - )}[chunkId] + "`; - }, - contentHash: { - [MODULE_TYPE]: `" + ${JSON.stringify( - chunkMaps.contentHash[MODULE_TYPE] - )}[chunkId] + "`, - }, - contentHashWithLength: { - [MODULE_TYPE]: (length) => { - const shortContentHashMap = {}; - const contentHash = chunkMaps.contentHash[MODULE_TYPE]; - - for (const chunkId of Object.keys(contentHash)) { - if (typeof contentHash[chunkId] === 'string') { - shortContentHashMap[chunkId] = contentHash[ - chunkId - ].substring(0, length); - } - } - - return `" + ${JSON.stringify( - shortContentHashMap - )}[chunkId] + "`; - }, - }, - name: `" + (${JSON.stringify( - chunkMaps.name - )}[chunkId]||chunkId) + "`, - }, - contentHashType: MODULE_TYPE, - } - ); - - 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");', - this.runtimeOptions.attributes - ? Template.asString( - Object.entries(this.runtimeOptions.attributes).map( - (entry) => { - const [key, value] = entry; - - return `linkTag.setAttribute(${JSON.stringify( - key - )}, ${JSON.stringify(value)});`; - } - ) - ) - : '', - 'linkTag.rel = "stylesheet";', - this.runtimeOptions.linkType - ? `linkTag.type = ${JSON.stringify( - this.runtimeOptions.linkType - )};` - : '', - 'var onLinkComplete = function (event) {', - Template.indent([ - '// avoid mem leaks.', - 'linkTag.onerror = linkTag.onload = null;', - "if (event.type === 'load') {", - Template.indent(['resolve();']), - '} else {', - Template.indent([ - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - 'var realHref = event && event.target && event.target.href || fullhref;', - 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + realHref + ")");', - 'err.code = "CSS_CHUNK_LOAD_FAILED";', - 'err.type = errorType;', - 'err.request = realHref;', - 'delete installedCssChunks[chunkId]', - 'linkTag.parentNode.removeChild(linkTag)', - 'reject(err);', - ]), - '}', - ]), - '};', - 'linkTag.onerror = linkTag.onload = onLinkComplete;', - 'linkTag.href = fullhref;', - crossOriginLoading - ? Template.asString([ - `if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, - Template.indent( - `linkTag.crossOrigin = ${JSON.stringify( - crossOriginLoading - )};` - ), - '}', - ]) - : '', - typeof this.runtimeOptions.insert !== 'undefined' - ? typeof this.runtimeOptions.insert === 'function' - ? `(${this.runtimeOptions.insert.toString()})(linkTag)` - : Template.asString([ - `var target = document.querySelector("${this.runtimeOptions.insert}");`, - `target.parentNode.insertBefore(linkTag, target.nextSibling);`, - ]) - : Template.asString([ - 'document.head.appendChild(linkTag);', - ]), - ]), - '}).then(function() {', - Template.indent(['installedCssChunks[chunkId] = 0;']), - '}));', - ]), - '}', - ]); + for (const chunk of mainChunk.getAllAsyncChunks()) { + const modules = chunkGraph.getOrderedChunkModulesIterable( + chunk, + compareModulesByIdentifier + ); + for (const module of modules) { + if (module.type === MODULE_TYPE) { + obj[chunk.id] = 1; + break; } - - return source; } - ); - } else { - const { RuntimeGlobals, runtime } = webpack; + } - // eslint-disable-next-line no-shadow - const getCssChunkObject = (mainChunk, compilation) => { - const obj = {}; - const { chunkGraph } = compilation; + return obj; + }; - for (const chunk of mainChunk.getAllAsyncChunks()) { - const modules = chunkGraph.getOrderedChunkModulesIterable( - chunk, - compareModulesByIdentifier - ); - for (const module of modules) { - if (module.type === MODULE_TYPE) { - obj[chunk.id] = 1; - break; - } - } - } + const { RuntimeModule } = webpack; - return obj; - }; + class CssLoadingRuntimeModule extends RuntimeModule { + constructor(runtimeRequirements, runtimeOptions) { + super('css loading', 10); - const { RuntimeModule } = webpack; + this.runtimeRequirements = runtimeRequirements; + this.runtimeOptions = runtimeOptions; + } - class CssLoadingRuntimeModule extends RuntimeModule { - constructor(runtimeRequirements, runtimeOptions) { - super('css loading', 10); + generate() { + const { chunk, runtimeRequirements } = this; + const { + runtimeTemplate, + outputOptions: { crossOriginLoading }, + } = this.compilation; + const chunkMap = getCssChunkObject(chunk, this.compilation); + + const withLoading = + runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && + Object.keys(chunkMap).length > 0; + const withHmr = runtimeRequirements.has( + RuntimeGlobals.hmrDownloadUpdateHandlers + ); - this.runtimeRequirements = runtimeRequirements; - this.runtimeOptions = runtimeOptions; + if (!withLoading && !withHmr) { + return null; } - generate() { - const { chunk, runtimeRequirements } = this; - const { - runtimeTemplate, - outputOptions: { crossOriginLoading }, - } = this.compilation; - const chunkMap = getCssChunkObject(chunk, this.compilation); - - const withLoading = - runtimeRequirements.has(RuntimeGlobals.ensureChunkHandlers) && - Object.keys(chunkMap).length > 0; - const withHmr = runtimeRequirements.has( - RuntimeGlobals.hmrDownloadUpdateHandlers - ); - - if (!withLoading && !withHmr) { - return null; - } - - return Template.asString([ - `var createStylesheet = ${runtimeTemplate.basicFunction( - 'chunkId, fullhref, resolve, reject', - [ - 'var linkTag = document.createElement("link");', - this.runtimeOptions.attributes - ? Template.asString( - Object.entries(this.runtimeOptions.attributes).map( - (entry) => { - const [key, value] = entry; - - return `linkTag.setAttribute(${JSON.stringify( - key - )}, ${JSON.stringify(value)});`; - } - ) + return Template.asString([ + `var createStylesheet = ${runtimeTemplate.basicFunction( + 'chunkId, fullhref, resolve, reject', + [ + 'var linkTag = document.createElement("link");', + this.runtimeOptions.attributes + ? Template.asString( + Object.entries(this.runtimeOptions.attributes).map( + (entry) => { + const [key, value] = entry; + + return `linkTag.setAttribute(${JSON.stringify( + key + )}, ${JSON.stringify(value)});`; + } ) - : '', - 'linkTag.rel = "stylesheet";', - this.runtimeOptions.linkType - ? `linkTag.type = ${JSON.stringify( - this.runtimeOptions.linkType - )};` - : '', - `var onLinkComplete = ${runtimeTemplate.basicFunction( - 'event', + ) + : '', + 'linkTag.rel = "stylesheet";', + this.runtimeOptions.linkType + ? `linkTag.type = ${JSON.stringify( + this.runtimeOptions.linkType + )};` + : '', + `var onLinkComplete = ${runtimeTemplate.basicFunction('event', [ + '// avoid mem leaks.', + 'linkTag.onerror = linkTag.onload = null;', + "if (event.type === 'load') {", + Template.indent(['resolve();']), + '} else {', + Template.indent([ + "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", + 'var realHref = event && event.target && event.target.href || fullhref;', + 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + realHref + ")");', + 'err.code = "CSS_CHUNK_LOAD_FAILED";', + 'err.type = errorType;', + 'err.request = realHref;', + 'linkTag.parentNode.removeChild(linkTag)', + 'reject(err);', + ]), + '}', + ])}`, + 'linkTag.onerror = linkTag.onload = onLinkComplete;', + 'linkTag.href = fullhref;', + crossOriginLoading + ? Template.asString([ + `if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, + Template.indent( + `linkTag.crossOrigin = ${JSON.stringify( + crossOriginLoading + )};` + ), + '}', + ]) + : '', + typeof this.runtimeOptions.insert !== 'undefined' + ? typeof this.runtimeOptions.insert === 'function' + ? `(${this.runtimeOptions.insert.toString()})(linkTag)` + : Template.asString([ + `var target = document.querySelector("${this.runtimeOptions.insert}");`, + `target.parentNode.insertBefore(linkTag, target.nextSibling);`, + ]) + : Template.asString(['document.head.appendChild(linkTag);']), + 'return linkTag;', + ] + )};`, + `var findStylesheet = ${runtimeTemplate.basicFunction( + 'href, fullhref', + [ + '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 tag;', + ]), + '}', + '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 tag;', + ]), + '}', + ] + )};`, + `var loadStylesheet = ${runtimeTemplate.basicFunction( + 'chunkId', + `return new Promise(${runtimeTemplate.basicFunction( + 'resolve, reject', + [ + `var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, + `var fullhref = ${RuntimeGlobals.publicPath} + href;`, + 'if(findStylesheet(href, fullhref)) return resolve();', + 'createStylesheet(chunkId, fullhref, resolve, reject);', + ] + )});` + )}`, + withLoading + ? Template.asString([ + '// object to store loaded CSS chunks', + 'var installedCssChunks = {', + Template.indent( + chunk.ids + .map((id) => `${JSON.stringify(id)}: 0`) + .join(',\n') + ), + '};', + '', + `${ + RuntimeGlobals.ensureChunkHandlers + }.miniCss = ${runtimeTemplate.basicFunction( + 'chunkId, promises', [ - '// avoid mem leaks.', - 'linkTag.onerror = linkTag.onload = null;', - "if (event.type === 'load') {", - Template.indent(['resolve();']), - '} else {', + `var cssChunks = ${JSON.stringify(chunkMap)};`, + 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', + 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', Template.indent([ - "var errorType = event && (event.type === 'load' ? 'missing' : event.type);", - 'var realHref = event && event.target && event.target.href || fullhref;', - 'var err = new Error("Loading CSS chunk " + chunkId + " failed.\\n(" + realHref + ")");', - 'err.code = "CSS_CHUNK_LOAD_FAILED";', - 'err.type = errorType;', - 'err.request = realHref;', - 'linkTag.parentNode.removeChild(linkTag)', - 'reject(err);', + `promises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(${runtimeTemplate.basicFunction( + '', + 'installedCssChunks[chunkId] = 0;' + )}, ${runtimeTemplate.basicFunction('e', [ + 'delete installedCssChunks[chunkId];', + 'throw e;', + ])}));`, ]), '}', ] - )}`, - 'linkTag.onerror = linkTag.onload = onLinkComplete;', - 'linkTag.href = fullhref;', - crossOriginLoading - ? Template.asString([ - `if (linkTag.href.indexOf(window.location.origin + '/') !== 0) {`, - Template.indent( - `linkTag.crossOrigin = ${JSON.stringify( - crossOriginLoading - )};` - ), - '}', - ]) - : '', - typeof this.runtimeOptions.insert !== 'undefined' - ? typeof this.runtimeOptions.insert === 'function' - ? `(${this.runtimeOptions.insert.toString()})(linkTag)` - : Template.asString([ - `var target = document.querySelector("${this.runtimeOptions.insert}");`, - `target.parentNode.insertBefore(linkTag, target.nextSibling);`, - ]) - : Template.asString([ - 'document.head.appendChild(linkTag);', - ]), - 'return linkTag;', - ] - )};`, - `var findStylesheet = ${runtimeTemplate.basicFunction( - 'href, fullhref', - [ - '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 tag;', - ]), - '}', - '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 tag;', - ]), - '}', - ] - )};`, - `var loadStylesheet = ${runtimeTemplate.basicFunction( - 'chunkId', - `return new Promise(${runtimeTemplate.basicFunction( - 'resolve, reject', - [ - `var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, - `var fullhref = ${RuntimeGlobals.publicPath} + href;`, - 'if(findStylesheet(href, fullhref)) return resolve();', - 'createStylesheet(chunkId, fullhref, resolve, reject);', - ] - )});` - )}`, - withLoading - ? Template.asString([ - '// object to store loaded CSS chunks', - 'var installedCssChunks = {', - Template.indent( - chunk.ids - .map((id) => `${JSON.stringify(id)}: 0`) - .join(',\n') - ), - '};', - '', - `${ - RuntimeGlobals.ensureChunkHandlers - }.miniCss = ${runtimeTemplate.basicFunction( - 'chunkId, promises', - [ - `var cssChunks = ${JSON.stringify(chunkMap)};`, - 'if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]);', - 'else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) {', + )};`, + ]) + : '// no chunk loading', + '', + withHmr + ? Template.asString([ + 'var oldTags = [];', + 'var newTags = [];', + `var applyHandler = ${runtimeTemplate.basicFunction( + 'options', + [ + `return { dispose: ${runtimeTemplate.basicFunction('', [ + 'for(var i = 0; i < oldTags.length; i++) {', Template.indent([ - `promises.push(installedCssChunks[chunkId] = loadStylesheet(chunkId).then(${runtimeTemplate.basicFunction( - '', - 'installedCssChunks[chunkId] = 0;' - )}, ${runtimeTemplate.basicFunction('e', [ - 'delete installedCssChunks[chunkId];', - 'throw e;', - ])}));`, + 'var oldTag = oldTags[i];', + 'if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);', ]), '}', - ] - )};`, - ]) - : '// no chunk loading', - '', - withHmr - ? Template.asString([ - 'var oldTags = [];', - 'var newTags = [];', - `var applyHandler = ${runtimeTemplate.basicFunction( - 'options', - [ - `return { dispose: ${runtimeTemplate.basicFunction('', [ - 'for(var i = 0; i < oldTags.length; i++) {', - Template.indent([ - 'var oldTag = oldTags[i];', - 'if(oldTag.parentNode) oldTag.parentNode.removeChild(oldTag);', - ]), - '}', - 'oldTags.length = 0;', - ])}, apply: ${runtimeTemplate.basicFunction('', [ - 'for(var i = 0; i < newTags.length; i++) newTags[i].rel = "stylesheet";', - 'newTags.length = 0;', - ])} };`, - ] - )}`, - `${ - RuntimeGlobals.hmrDownloadUpdateHandlers - }.miniCss = ${runtimeTemplate.basicFunction( - 'chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList', - [ - 'applyHandlers.push(applyHandler);', - `chunkIds.forEach(${runtimeTemplate.basicFunction( - 'chunkId', - [ - `var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, - `var fullhref = ${RuntimeGlobals.publicPath} + href;`, - 'var oldTag = findStylesheet(href, fullhref);', - 'if(!oldTag) return;', - `promises.push(new Promise(${runtimeTemplate.basicFunction( - 'resolve, reject', - [ - `var tag = createStylesheet(chunkId, fullhref, ${runtimeTemplate.basicFunction( - '', - [ - 'tag.as = "style";', - 'tag.rel = "preload";', - 'resolve();', - ] - )}, reject);`, - 'oldTags.push(oldTag);', - 'newTags.push(tag);', - ] - )}));`, - ] - )});`, - ] - )}`, - ]) - : '// no hmr', - ]); - } + 'oldTags.length = 0;', + ])}, apply: ${runtimeTemplate.basicFunction('', [ + 'for(var i = 0; i < newTags.length; i++) newTags[i].rel = "stylesheet";', + 'newTags.length = 0;', + ])} };`, + ] + )}`, + `${ + RuntimeGlobals.hmrDownloadUpdateHandlers + }.miniCss = ${runtimeTemplate.basicFunction( + 'chunkIds, removedChunks, removedModules, promises, applyHandlers, updatedModulesList', + [ + 'applyHandlers.push(applyHandler);', + `chunkIds.forEach(${runtimeTemplate.basicFunction( + 'chunkId', + [ + `var href = ${RuntimeGlobals.require}.miniCssF(chunkId);`, + `var fullhref = ${RuntimeGlobals.publicPath} + href;`, + 'var oldTag = findStylesheet(href, fullhref);', + 'if(!oldTag) return;', + `promises.push(new Promise(${runtimeTemplate.basicFunction( + 'resolve, reject', + [ + `var tag = createStylesheet(chunkId, fullhref, ${runtimeTemplate.basicFunction( + '', + [ + 'tag.as = "style";', + 'tag.rel = "preload";', + 'resolve();', + ] + )}, reject);`, + 'oldTags.push(oldTag);', + 'newTags.push(tag);', + ] + )}));`, + ] + )});`, + ] + )}`, + ]) + : '// no hmr', + ]); } + } - const enabledChunks = new WeakSet(); - - const handler = (chunk, set) => { - if (enabledChunks.has(chunk)) { - return; - } + const enabledChunks = new WeakSet(); - enabledChunks.add(chunk); + const handler = (chunk, set) => { + if (enabledChunks.has(chunk)) { + return; + } - if ( - typeof this.options.chunkFilename === 'string' && - /\[(full)?hash(:\d+)?\]/.test(this.options.chunkFilename) - ) { - set.add(RuntimeGlobals.getFullHash); - } + enabledChunks.add(chunk); - set.add(RuntimeGlobals.publicPath); + if ( + typeof this.options.chunkFilename === 'string' && + /\[(full)?hash(:\d+)?\]/.test(this.options.chunkFilename) + ) { + set.add(RuntimeGlobals.getFullHash); + } - compilation.addRuntimeModule( - chunk, - new runtime.GetChunkFilenameRuntimeModule( - MODULE_TYPE, - 'mini-css', - `${RuntimeGlobals.require}.miniCssF`, - (referencedChunk) => { - if (!referencedChunk.contentHash[MODULE_TYPE]) { - return false; - } + set.add(RuntimeGlobals.publicPath); - return referencedChunk.canBeInitial() - ? this.options.filename - : this.options.chunkFilename; - }, - true - ) - ); + compilation.addRuntimeModule( + chunk, + new runtime.GetChunkFilenameRuntimeModule( + MODULE_TYPE, + 'mini-css', + `${RuntimeGlobals.require}.miniCssF`, + (referencedChunk) => { + if (!referencedChunk.contentHash[MODULE_TYPE]) { + return false; + } - compilation.addRuntimeModule( - chunk, - new CssLoadingRuntimeModule(set, this.runtimeOptions) - ); - }; + return referencedChunk.canBeInitial() + ? this.options.filename + : this.options.chunkFilename; + }, + true + ) + ); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.ensureChunkHandlers) - .tap(pluginName, handler); - compilation.hooks.runtimeRequirementInTree - .for(RuntimeGlobals.hmrDownloadUpdateHandlers) - .tap(pluginName, handler); - } + compilation.addRuntimeModule( + chunk, + new CssLoadingRuntimeModule(set, this.runtimeOptions) + ); + }; + + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.ensureChunkHandlers) + .tap(pluginName, handler); + compilation.hooks.runtimeRequirementInTree + .for(RuntimeGlobals.hmrDownloadUpdateHandlers) + .tap(pluginName, handler); }); } @@ -1124,22 +789,6 @@ class MiniCssExtractPlugin { : chunk.modulesIterable; } - getCssChunkObject(mainChunk, compilation) { - const obj = {}; - const { chunkGraph } = compilation; - - for (const chunk of mainChunk.getAllAsyncChunks()) { - for (const module of this.getChunkModules(chunk, chunkGraph)) { - if (module.type === MODULE_TYPE) { - obj[chunk.id] = 1; - break; - } - } - } - - return obj; - } - sortModules(compilation, chunk, modules, requestShortener) { let usedModules = this._sortedModulesCache.get(chunk); @@ -1148,143 +797,128 @@ class MiniCssExtractPlugin { } const modulesList = [...modules]; - - const [chunkGroup] = chunk.groupsIterable; const moduleIndexFunctionName = typeof compilation.chunkGraph !== 'undefined' ? 'getModulePostOrderIndex' : 'getModuleIndex2'; - - if (typeof chunkGroup[moduleIndexFunctionName] === 'function') { - // Store dependencies for modules - const moduleDependencies = new Map( - modulesList.map((m) => [m, new Set()]) - ); - const moduleDependenciesReasons = new Map( - modulesList.map((m) => [m, new Map()]) - ); - - // Get ordered list of modules per chunk group - // This loop also gathers dependencies from the ordered lists - // Lists are in reverse order to allow to use Array.pop() - const modulesByChunkGroup = Array.from(chunk.groupsIterable, (cg) => { - const sortedModules = modulesList - .map((m) => { - return { - module: m, - index: cg[moduleIndexFunctionName](m), - }; - }) - // eslint-disable-next-line no-undefined - .filter((item) => item.index !== undefined) - .sort((a, b) => b.index - a.index) - .map((item) => item.module); - - for (let i = 0; i < sortedModules.length; i++) { - const set = moduleDependencies.get(sortedModules[i]); - const reasons = moduleDependenciesReasons.get(sortedModules[i]); - - for (let j = i + 1; j < sortedModules.length; j++) { - const module = sortedModules[j]; - set.add(module); - const reason = reasons.get(module) || new Set(); - reason.add(cg); - reasons.set(module, reason); - } + // Store dependencies for modules + const moduleDependencies = new Map(modulesList.map((m) => [m, new Set()])); + const moduleDependenciesReasons = new Map( + modulesList.map((m) => [m, new Map()]) + ); + // Get ordered list of modules per chunk group + // This loop also gathers dependencies from the ordered lists + // Lists are in reverse order to allow to use Array.pop() + const modulesByChunkGroup = Array.from(chunk.groupsIterable, (cg) => { + const sortedModules = modulesList + .map((m) => { + return { + module: m, + index: cg[moduleIndexFunctionName](m), + }; + }) + // eslint-disable-next-line no-undefined + .filter((item) => item.index !== undefined) + .sort((a, b) => b.index - a.index) + .map((item) => item.module); + + for (let i = 0; i < sortedModules.length; i++) { + const set = moduleDependencies.get(sortedModules[i]); + const reasons = moduleDependenciesReasons.get(sortedModules[i]); + + for (let j = i + 1; j < sortedModules.length; j++) { + const module = sortedModules[j]; + set.add(module); + const reason = reasons.get(module) || new Set(); + reason.add(cg); + reasons.set(module, reason); } + } - return sortedModules; - }); - - // set with already included modules in correct order - usedModules = new Set(); + return sortedModules; + }); - const unusedModulesFilter = (m) => !usedModules.has(m); + // set with already included modules in correct order + usedModules = new Set(); - while (usedModules.size < modulesList.length) { - let success = false; - let bestMatch; - let bestMatchDeps; + const unusedModulesFilter = (m) => !usedModules.has(m); - // get first module where dependencies are fulfilled - for (const list of modulesByChunkGroup) { - // skip and remove already added modules - while (list.length > 0 && usedModules.has(list[list.length - 1])) { - list.pop(); - } + while (usedModules.size < modulesList.length) { + let success = false; + let bestMatch; + let bestMatchDeps; - // skip empty lists - if (list.length !== 0) { - const module = list[list.length - 1]; - const deps = moduleDependencies.get(module); - // determine dependencies that are not yet included - const failedDeps = Array.from(deps).filter(unusedModulesFilter); - - // store best match for fallback behavior - if (!bestMatchDeps || bestMatchDeps.length > failedDeps.length) { - bestMatch = list; - bestMatchDeps = failedDeps; - } - - if (failedDeps.length === 0) { - // use this module and remove it from list - usedModules.add(list.pop()); - success = true; - break; - } - } + // get first module where dependencies are fulfilled + for (const list of modulesByChunkGroup) { + // skip and remove already added modules + while (list.length > 0 && usedModules.has(list[list.length - 1])) { + list.pop(); } - if (!success) { - // no module found => there is a conflict - // use list with fewest failed deps - // and emit a warning - const fallbackModule = bestMatch.pop(); + // skip empty lists + if (list.length !== 0) { + const module = list[list.length - 1]; + const deps = moduleDependencies.get(module); + // determine dependencies that are not yet included + const failedDeps = Array.from(deps).filter(unusedModulesFilter); + + // store best match for fallback behavior + if (!bestMatchDeps || bestMatchDeps.length > failedDeps.length) { + bestMatch = list; + bestMatchDeps = failedDeps; + } - if (!this.options.ignoreOrder) { - const reasons = moduleDependenciesReasons.get(fallbackModule); - 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) => { - const goodReasonsMap = moduleDependenciesReasons.get(m); - const goodReasons = - goodReasonsMap && goodReasonsMap.get(fallbackModule); - const failedChunkGroups = Array.from( - reasons.get(m), - (cg) => cg.name - ).join(', '); - const goodChunkGroups = - goodReasons && - Array.from(goodReasons, (cg) => cg.name).join(', '); - 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'); - }), - ].join('\n') - ) - ); + if (failedDeps.length === 0) { + // use this module and remove it from list + usedModules.add(list.pop()); + success = true; + break; } + } + } - usedModules.add(fallbackModule); + if (!success) { + // no module found => there is a conflict + // use list with fewest failed deps + // and emit a warning + const fallbackModule = bestMatch.pop(); + + if (!this.options.ignoreOrder) { + const reasons = moduleDependenciesReasons.get(fallbackModule); + 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) => { + const goodReasonsMap = moduleDependenciesReasons.get(m); + const goodReasons = + goodReasonsMap && goodReasonsMap.get(fallbackModule); + const failedChunkGroups = Array.from( + reasons.get(m), + (cg) => cg.name + ).join(', '); + const goodChunkGroups = + goodReasons && + Array.from(goodReasons, (cg) => cg.name).join(', '); + 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'); + }), + ].join('\n') + ) + ); } + + usedModules.add(fallbackModule); } - } else { - // fallback for older webpack versions - // (to avoid a breaking change) - // TODO remove this in next major version - // and increase minimum webpack version to 4.12.0 - modulesList.sort((a, b) => a.index2 - b.index2); - usedModules = modulesList; } this._sortedModulesCache.set(chunk, usedModules); @@ -1292,7 +926,15 @@ class MiniCssExtractPlugin { return usedModules; } - renderContentAsset(compiler, compilation, chunk, modules, requestShortener) { + renderContentAsset( + compiler, + compilation, + chunk, + modules, + requestShortener, + filenameTemplate, + pathData + ) { const usedModules = this.sortModules( compilation, chunk, @@ -1300,12 +942,8 @@ class MiniCssExtractPlugin { requestShortener ); - // TODO remove after drop webpack v4 - const { ConcatSource, SourceMapSource, RawSource } = compiler.webpack - ? compiler.webpack.sources - : // eslint-disable-next-line global-require - require('webpack-sources'); - + const { ConcatSource, SourceMapSource, RawSource } = + compiler.webpack.sources; const source = new ConcatSource(); const externalsSource = new ConcatSource(); @@ -1329,6 +967,15 @@ class MiniCssExtractPlugin { source.add(`@media ${m.media} {\n`); } + const { path: filename } = compilation.getPathWithInfo( + filenameTemplate, + pathData + ); + + const undoPath = getUndoPath(filename, compiler.outputPath, false); + + content = content.replace(new RegExp(AUTO_PUBLIC_PATH, 'g'), undoPath); + if (m.sourceMap) { source.add( new SourceMapSource( diff --git a/src/loader.js b/src/loader.js index c6a5cecf..9400366f 100644 --- a/src/loader.js +++ b/src/loader.js @@ -3,7 +3,7 @@ import path from 'path'; import loaderUtils from 'loader-utils'; import { validate } from 'schema-utils'; -import { findModuleById, evalModuleCode } from './utils'; +import { findModuleById, evalModuleCode, AUTO_PUBLIC_PATH } from './utils'; import schema from './loader-options.json'; import MiniCssExtractPlugin, { pluginName, pluginSymbol } from './index'; @@ -50,9 +50,7 @@ export function pitch(request) { return; } - // TODO simplify after drop webpack v4 - // eslint-disable-next-line global-require - const webpack = this._compiler.webpack || require('webpack'); + const { webpack } = this._compiler; const handleExports = (originalExports, compilation, assets, assetsInfo) => { let locals; @@ -176,18 +174,18 @@ export function pitch(request) { return callback(null, resultSource); }; - const publicPath = - typeof options.publicPath === 'string' - ? options.publicPath === 'auto' - ? '' - : options.publicPath === '' || options.publicPath.endsWith('/') - ? options.publicPath - : `${options.publicPath}/` - : typeof options.publicPath === 'function' - ? options.publicPath(this.resourcePath, this.rootContext) - : this._compilation.outputOptions.publicPath === 'auto' - ? '' - : this._compilation.outputOptions.publicPath; + let { publicPath } = this._compilation.outputOptions; + + if (typeof options.publicPath === 'string') { + // eslint-disable-next-line prefer-destructuring + publicPath = options.publicPath; + } else if (typeof options.publicPath === 'function') { + publicPath = options.publicPath(this.resourcePath, this.rootContext); + } + + if (publicPath === 'auto') { + publicPath = AUTO_PUBLIC_PATH; + } if (optionsFromPlugin.experimentalUseImportModule) { if (!this.importModule) { @@ -246,56 +244,38 @@ export function pitch(request) { }; const { NodeTemplatePlugin } = webpack.node; - const NodeTargetPlugin = webpack.node.NodeTargetPlugin - ? webpack.node.NodeTargetPlugin - : // eslint-disable-next-line global-require - require('webpack/lib/node/NodeTargetPlugin'); + const { NodeTargetPlugin } = webpack.node; new NodeTemplatePlugin(outputOptions).apply(childCompiler); new NodeTargetPlugin().apply(childCompiler); const { EntryOptionPlugin } = webpack; - if (EntryOptionPlugin) { - const { - library: { EnableLibraryPlugin }, - } = webpack; + const { + library: { EnableLibraryPlugin }, + } = webpack; - new EnableLibraryPlugin('commonjs2').apply(childCompiler); + new EnableLibraryPlugin('commonjs2').apply(childCompiler); - EntryOptionPlugin.applyEntryOption(childCompiler, this.context, { - child: { - library: { - type: 'commonjs2', - }, - import: [`!!${request}`], + EntryOptionPlugin.applyEntryOption(childCompiler, this.context, { + child: { + library: { + type: 'commonjs2', }, - }); - } else { - const { LibraryTemplatePlugin, SingleEntryPlugin } = webpack; - - new LibraryTemplatePlugin(null, 'commonjs2').apply(childCompiler); - new SingleEntryPlugin(this.context, `!!${request}`, pluginName).apply( - childCompiler - ); - } - + import: [`!!${request}`], + }, + }); const { LimitChunkCountPlugin } = webpack.optimize; new LimitChunkCountPlugin({ maxChunks: 1 }).apply(childCompiler); - const NormalModule = webpack.NormalModule - ? webpack.NormalModule - : // eslint-disable-next-line global-require - require('webpack/lib/NormalModule'); + const { NormalModule } = webpack; childCompiler.hooks.thisCompilation.tap( `${pluginName} loader`, (compilation) => { const normalModuleHook = - typeof NormalModule.getCompilationHooks !== 'undefined' - ? NormalModule.getCompilationHooks(compilation).loader - : compilation.hooks.normalModuleLoader; + NormalModule.getCompilationHooks(compilation).loader; normalModuleHook.tap(`${pluginName} loader`, (loaderContext, module) => { if (module.request === request) { @@ -314,12 +294,8 @@ export function pitch(request) { let source; - const isWebpack4 = childCompiler.webpack - ? false - : typeof childCompiler.resolvers !== 'undefined'; - - if (isWebpack4) { - childCompiler.hooks.afterCompile.tap(pluginName, (compilation) => { + childCompiler.hooks.compilation.tap(pluginName, (compilation) => { + compilation.hooks.processAssets.tap(pluginName, () => { source = compilation.assets[childFilename] && compilation.assets[childFilename].source(); @@ -327,28 +303,11 @@ export function pitch(request) { // Remove all chunk assets compilation.chunks.forEach((chunk) => { chunk.files.forEach((file) => { - delete compilation.assets[file]; // eslint-disable-line no-param-reassign - }); - }); - }); - } else { - childCompiler.hooks.compilation.tap(pluginName, (compilation) => { - compilation.hooks.processAssets.tap(pluginName, () => { - source = - compilation.assets[childFilename] && - compilation.assets[childFilename].source(); - - // console.log(source); - - // Remove all chunk assets - compilation.chunks.forEach((chunk) => { - chunk.files.forEach((file) => { - compilation.deleteAsset(file); - }); + compilation.deleteAsset(file); }); }); }); - } + }); childCompiler.runAsChild((error, entries, compilation) => { const assets = Object.create(null); diff --git a/src/utils.js b/src/utils.js index 772cd22d..38f983ee 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,6 +1,7 @@ import NativeModule from 'module'; const MODULE_TYPE = 'css/mini-extract'; +const AUTO_PUBLIC_PATH = '__MINI_CSS_EXTRACT_PLUGIN_PUBLIC_PATH__'; function findModuleById(compilation, id) { const { modules, chunkGraph } = compilation; @@ -51,6 +52,7 @@ function compareModulesByIdentifier(a, b) { export { MODULE_TYPE, + AUTO_PUBLIC_PATH, findModuleById, evalModuleCode, compareModulesByIdentifier, diff --git a/test/TestCache.test.js b/test/TestCache.test.js index c1409b94..7ebb2cd2 100644 --- a/test/TestCache.test.js +++ b/test/TestCache.test.js @@ -13,541 +13,521 @@ describe('TestCache', () => { }); it('should work without cache', async () => { - if (webpack.version[0] !== '4') { - const casesDirectory = path.resolve(__dirname, 'cases'); - const directoryForCase = path.resolve(casesDirectory, 'asset-modules'); - // eslint-disable-next-line import/no-dynamic-require, global-require - const webpackConfig = require(path.resolve( - directoryForCase, - 'webpack.config.js' - )); - const outputPath = path.resolve(__dirname, 'js/cache-false'); - - await del([outputPath]); - - const compiler1 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: false, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + const casesDirectory = path.resolve(__dirname, 'cases'); + const directoryForCase = path.resolve(casesDirectory, 'asset-modules'); + // eslint-disable-next-line import/no-dynamic-require, global-require + const webpackConfig = require(path.resolve( + directoryForCase, + 'webpack.config.js' + )); + const outputPath = path.resolve(__dirname, 'js/cache-false'); + + await del([outputPath]); + + const compiler1 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: false, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(Array.from(stats.compilation.emittedAssets).sort()) - .toMatchInlineSnapshot(` + expect(Array.from(stats.compilation.emittedAssets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); - resolve(); - }); + resolve(); }); }); - - const compiler2 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: false, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler2.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + }); + + const compiler2 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: false, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchInlineSnapshot(`Array []`); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); - - resolve(); - }); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchInlineSnapshot(`Array []`); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); + + resolve(); }); }); - } else { - expect(true).toBe(true); - } + }); }); it('should work with the "memory" cache', async () => { - if (webpack.version[0] !== '4') { - const casesDirectory = path.resolve(__dirname, 'cases'); - const directoryForCase = path.resolve(casesDirectory, 'asset-modules'); - // eslint-disable-next-line import/no-dynamic-require, global-require - const webpackConfig = require(path.resolve( - directoryForCase, - 'webpack.config.js' - )); - const outputPath = path.resolve(__dirname, 'js/cache-memory'); - - await del([outputPath]); - - const compiler1 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'memory', - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + const casesDirectory = path.resolve(__dirname, 'cases'); + const directoryForCase = path.resolve(casesDirectory, 'asset-modules'); + // eslint-disable-next-line import/no-dynamic-require, global-require + const webpackConfig = require(path.resolve( + directoryForCase, + 'webpack.config.js' + )); + const outputPath = path.resolve(__dirname, 'js/cache-memory'); + + await del([outputPath]); + + const compiler1 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'memory', + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(Array.from(stats.compilation.emittedAssets).sort()) - .toMatchInlineSnapshot(` + expect(Array.from(stats.compilation.emittedAssets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); - resolve(); - }); + resolve(); }); }); - - const compiler2 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'memory', - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler2.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + }); + + const compiler2 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'memory', + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchInlineSnapshot(`Array []`); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); - - resolve(); - }); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchInlineSnapshot(`Array []`); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); + + resolve(); }); }); - } else { - expect(true).toBe(true); - } + }); }); it('should work with the "filesystem" cache', async () => { - if (webpack.version[0] !== '4') { - const casesDirectory = path.resolve(__dirname, 'cases'); - const directoryForCase = path.resolve(casesDirectory, 'simple'); - // eslint-disable-next-line import/no-dynamic-require, global-require - const webpackConfig = require(path.resolve( - directoryForCase, - 'webpack.config.js' - )); - const outputPath = path.resolve(__dirname, 'js/cache-filesystem'); - const fileSystemCacheDirectory = path.resolve( - __dirname, - './js/.cache/type-filesystem' - ); - - await del([outputPath, fileSystemCacheDirectory]); - - const compiler1 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'filesystem', - cacheDirectory: fileSystemCacheDirectory, - idleTimeout: 0, - idleTimeoutForInitialStore: 0, - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + const casesDirectory = path.resolve(__dirname, 'cases'); + const directoryForCase = path.resolve(casesDirectory, 'simple'); + // eslint-disable-next-line import/no-dynamic-require, global-require + const webpackConfig = require(path.resolve( + directoryForCase, + 'webpack.config.js' + )); + const outputPath = path.resolve(__dirname, 'js/cache-filesystem'); + const fileSystemCacheDirectory = path.resolve( + __dirname, + './js/.cache/type-filesystem' + ); + + await del([outputPath, fileSystemCacheDirectory]); + + const compiler1 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'filesystem', + cacheDirectory: fileSystemCacheDirectory, + idleTimeout: 0, + idleTimeoutForInitialStore: 0, + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", ] `); - expect(Array.from(stats.compilation.emittedAssets).sort()) - .toMatchInlineSnapshot(` + expect(Array.from(stats.compilation.emittedAssets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", ] `); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); - resolve(); - }); + resolve(); }); }); - - const compiler2 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'filesystem', - cacheDirectory: fileSystemCacheDirectory, - idleTimeout: 0, - idleTimeoutForInitialStore: 0, - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler2.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + }); + + const compiler2 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'filesystem', + cacheDirectory: fileSystemCacheDirectory, + idleTimeout: 0, + idleTimeoutForInitialStore: 0, + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", ] `); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchInlineSnapshot(`Array []`); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); - - resolve(); - }); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchInlineSnapshot(`Array []`); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); + + resolve(); }); }); - } else { - expect(true).toBe(true); - } + }); }); it('should work with the "filesystem" cache and asset modules', async () => { - if (webpack.version[0] !== '4') { - const casesDirectory = path.resolve(__dirname, 'cases'); - const directoryForCase = path.resolve(casesDirectory, 'asset-modules'); - // eslint-disable-next-line import/no-dynamic-require, global-require - const webpackConfig = require(path.resolve( - directoryForCase, - 'webpack.config.js' - )); - const outputPath = path.resolve( - __dirname, - 'js/cache-filesystem-asset-modules' - ); - const fileSystemCacheDirectory = path.resolve( - __dirname, - './js/.cache/type-filesystem' - ); - - await del([outputPath, fileSystemCacheDirectory]); - - const compiler1 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'filesystem', - cacheDirectory: fileSystemCacheDirectory, - idleTimeout: 0, - idleTimeoutForInitialStore: 0, - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + const casesDirectory = path.resolve(__dirname, 'cases'); + const directoryForCase = path.resolve(casesDirectory, 'asset-modules'); + // eslint-disable-next-line import/no-dynamic-require, global-require + const webpackConfig = require(path.resolve( + directoryForCase, + 'webpack.config.js' + )); + const outputPath = path.resolve( + __dirname, + 'js/cache-filesystem-asset-modules' + ); + const fileSystemCacheDirectory = path.resolve( + __dirname, + './js/.cache/type-filesystem' + ); + + await del([outputPath, fileSystemCacheDirectory]); + + const compiler1 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'filesystem', + cacheDirectory: fileSystemCacheDirectory, + idleTimeout: 0, + idleTimeoutForInitialStore: 0, + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(Array.from(stats.compilation.emittedAssets).sort()) - .toMatchInlineSnapshot(` + expect(Array.from(stats.compilation.emittedAssets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); - resolve(); - }); + resolve(); }); }); - - const compiler2 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'filesystem', - cacheDirectory: fileSystemCacheDirectory, - idleTimeout: 0, - idleTimeoutForInitialStore: 0, - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler2.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + }); + + const compiler2 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'filesystem', + cacheDirectory: fileSystemCacheDirectory, + idleTimeout: 0, + idleTimeoutForInitialStore: 0, + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchInlineSnapshot(`Array []`); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); - - resolve(); - }); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchInlineSnapshot(`Array []`); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); + + resolve(); }); }); - } else { - expect(true).toBe(true); - } + }); }); it('should work with the "filesystem" cache and file-loader', async () => { - if (webpack.version[0] !== '4') { - const casesDirectory = path.resolve(__dirname, 'cases'); - const directoryForCase = path.resolve(casesDirectory, 'file-loader'); - // eslint-disable-next-line import/no-dynamic-require, global-require - const webpackConfig = require(path.resolve( - directoryForCase, - 'webpack.config.js' - )); - const outputPath = path.resolve( - __dirname, - 'js/cache-filesystem-file-loader' - ); - const fileSystemCacheDirectory = path.resolve( - __dirname, - './js/.cache/type-filesystem' - ); - - await del([outputPath, fileSystemCacheDirectory]); - - const compiler1 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'filesystem', - cacheDirectory: fileSystemCacheDirectory, - idleTimeout: 0, - idleTimeoutForInitialStore: 0, - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + const casesDirectory = path.resolve(__dirname, 'cases'); + const directoryForCase = path.resolve(casesDirectory, 'file-loader'); + // eslint-disable-next-line import/no-dynamic-require, global-require + const webpackConfig = require(path.resolve( + directoryForCase, + 'webpack.config.js' + )); + const outputPath = path.resolve( + __dirname, + 'js/cache-filesystem-file-loader' + ); + const fileSystemCacheDirectory = path.resolve( + __dirname, + './js/.cache/type-filesystem' + ); + + await del([outputPath, fileSystemCacheDirectory]); + + const compiler1 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'filesystem', + cacheDirectory: fileSystemCacheDirectory, + idleTimeout: 0, + idleTimeoutForInitialStore: 0, + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(Array.from(stats.compilation.emittedAssets).sort()) - .toMatchInlineSnapshot(` + expect(Array.from(stats.compilation.emittedAssets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); - resolve(); - }); + resolve(); }); }); - - const compiler2 = webpack({ - ...webpackConfig, - mode: 'development', - context: directoryForCase, - cache: { - type: 'filesystem', - cacheDirectory: fileSystemCacheDirectory, - idleTimeout: 0, - idleTimeoutForInitialStore: 0, - }, - output: { - path: outputPath, - }, - }); - - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler2.close(() => { - expect(Object.keys(stats.compilation.assets).sort()) - .toMatchInlineSnapshot(` + }); + + const compiler2 = webpack({ + ...webpackConfig, + mode: 'development', + context: directoryForCase, + cache: { + type: 'filesystem', + cacheDirectory: fileSystemCacheDirectory, + idleTimeout: 0, + idleTimeoutForInitialStore: 0, + }, + output: { + path: outputPath, + }, + }); + + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()) + .toMatchInlineSnapshot(` Array [ "main.css", "main.js", "static/react.svg", ] `); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchInlineSnapshot(`Array []`); - expect(stats.compilation.warnings).toHaveLength(0); - expect(stats.compilation.errors).toHaveLength(0); - - resolve(); - }); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchInlineSnapshot(`Array []`); + expect(stats.compilation.warnings).toHaveLength(0); + expect(stats.compilation.errors).toHaveLength(0); + + resolve(); }); }); - } else { - expect(true).toBe(true); - } + }); }); }); diff --git a/test/TestCases.test.js b/test/TestCases.test.js index 99e99b75..f9d70513 100644 --- a/test/TestCases.test.js +++ b/test/TestCases.test.js @@ -206,28 +206,16 @@ describe('TestCases', () => { res = res.replace(dateRegexp, ''); - if (webpack.version[0] === '4') { - const matchAll = res.match(/var hotCurrentHash = "([\d\w].*)"/i); - const replacer = new Array(matchAll[1].length); - - res = res.replace( - /var hotCurrentHash = "([\d\w].*)"/i, - `var hotCurrentHash = "${replacer.fill('x').join('')}"` - ); - } else { - const matchAll = res.match( - /__webpack_require__\.h = \(\) => \(("[\d\w].*")\)/i - ); + const matchAll = res.match( + /__webpack_require__\.h = \(\) => \(("[\d\w].*")\)/i + ); - const replacer = new Array(matchAll[1].length); + const replacer = new Array(matchAll[1].length); - res = res.replace( - /__webpack_require__\.h = \(\) => \(("[\d\w].*")\)/i, - `__webpack_require__.h = () => ("${replacer - .fill('x') - .join('')}")` - ); - } + res = res.replace( + /__webpack_require__\.h = \(\) => \(("[\d\w].*")\)/i, + `__webpack_require__.h = () => ("${replacer.fill('x').join('')}")` + ); fs.writeFileSync( path.resolve(outputDirectoryForCase, 'main.js'), diff --git a/test/TestMemoryFS.test.js b/test/TestMemoryFS.test.js index 8d55a166..db79d4f9 100644 --- a/test/TestMemoryFS.test.js +++ b/test/TestMemoryFS.test.js @@ -20,11 +20,8 @@ describe('TestMemoryFS', () => { context: directoryForCase, cache: false, }); - const outputFileSystem = createFsFromVolume(new Volume()); - // Todo remove when we drop webpack@4 support - outputFileSystem.join = path.join.bind(path); - compiler.outputFileSystem = outputFileSystem; + compiler.outputFileSystem = createFsFromVolume(new Volume()); compiler.run((err1, stats1) => { if (err1) { diff --git a/test/__snapshots__/HMR.test.js.snap.webpack4 b/test/__snapshots__/HMR.test.js.snap similarity index 100% rename from test/__snapshots__/HMR.test.js.snap.webpack4 rename to test/__snapshots__/HMR.test.js.snap diff --git a/test/__snapshots__/HMR.test.js.snap.webpack5 b/test/__snapshots__/HMR.test.js.snap.webpack5 deleted file mode 100644 index bf306c32..00000000 --- a/test/__snapshots__/HMR.test.js.snap.webpack5 +++ /dev/null @@ -1,43 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`HMR should handle error event 1`] = `"[HMR] css reload %s"`; - -exports[`HMR should handle error event 2`] = `""`; - -exports[`HMR should reloads with # link href 1`] = `"[HMR] css reload %s"`; - -exports[`HMR should reloads with # link href 2`] = `""`; - -exports[`HMR should reloads with absolute remove url 1`] = `"[HMR] css reload %s"`; - -exports[`HMR should reloads with absolute remove url 2`] = `""`; - -exports[`HMR should reloads with link without href 1`] = `"[HMR] css reload %s"`; - -exports[`HMR should reloads with link without href 2`] = `""`; - -exports[`HMR should reloads with locals 1`] = `"[HMR] Detected local css modules. Reload all css"`; - -exports[`HMR should reloads with locals 2`] = `""`; - -exports[`HMR should reloads with non http/https link href 1`] = `"[HMR] css reload %s"`; - -exports[`HMR should reloads with non http/https link href 2`] = `""`; - -exports[`HMR should reloads with non-file script in the end of page 1`] = `"[HMR] Reload all css"`; - -exports[`HMR should reloads with non-file script in the end of page 2`] = `""`; - -exports[`HMR should work reload all css 1`] = `"[HMR] Reload all css"`; - -exports[`HMR should work reload all css 2`] = `""`; - -exports[`HMR should works 1`] = `"[HMR] css reload %s"`; - -exports[`HMR should works 2`] = `""`; - -exports[`HMR should works with multiple updates 1`] = `"[HMR] css reload %s"`; - -exports[`HMR should works with multiple updates 2`] = `""`; - -exports[`HMR should works with multiple updates 3`] = `""`; diff --git a/test/__snapshots__/attributes-option.test.js.snap.webpack4 b/test/__snapshots__/attributes-option.test.js.snap similarity index 100% rename from test/__snapshots__/attributes-option.test.js.snap.webpack4 rename to test/__snapshots__/attributes-option.test.js.snap diff --git a/test/__snapshots__/attributes-option.test.js.snap.webpack5 b/test/__snapshots__/attributes-option.test.js.snap.webpack5 deleted file mode 100644 index 84007ca0..00000000 --- a/test/__snapshots__/attributes-option.test.js.snap.webpack5 +++ /dev/null @@ -1,37 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`attributes option should work with attributes option: DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`attributes option should work with attributes option: errors 1`] = `Array []`; - -exports[`attributes option should work with attributes option: warnings 1`] = `Array []`; - -exports[`attributes option should work without attributes option: DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`attributes option should work without attributes option: errors 1`] = `Array []`; - -exports[`attributes option should work without attributes option: warnings 1`] = `Array []`; diff --git a/test/__snapshots__/emit-option.test.js.snap.webpack5 b/test/__snapshots__/emit-option.test.js.snap similarity index 100% rename from test/__snapshots__/emit-option.test.js.snap.webpack5 rename to test/__snapshots__/emit-option.test.js.snap diff --git a/test/__snapshots__/emit-option.test.js.snap.webpack4 b/test/__snapshots__/emit-option.test.js.snap.webpack4 deleted file mode 100644 index 6608229e..00000000 --- a/test/__snapshots__/emit-option.test.js.snap.webpack4 +++ /dev/null @@ -1,52 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`emit option should work when emit option is "false": assets 1`] = ` -Array [ - "main.js", - "react.svg", -] -`; - -exports[`emit option should work when emit option is "false": errors 1`] = `Array []`; - -exports[`emit option should work when emit option is "false": warnings 1`] = `Array []`; - -exports[`emit option should work when emit option is "true": assets 1`] = ` -Array [ - "main.css", - "main.js", - "react.svg", -] -`; - -exports[`emit option should work when emit option is "true": errors 1`] = `Array []`; - -exports[`emit option should work when emit option is "true": warnings 1`] = `Array []`; - -exports[`emit option should work with locals when emit option is "false": DOM 1`] = ` -" - style-loader test - - - -css.foo: _1F17fUrdX_cbcyDHpFqmAD -css.bar: _3TZVxmkrZR2cTfifKhDoZn -css.baz: M-pzkE59YBii7EXzFyxE6 -" -`; - -exports[`emit option should work with locals when emit option is "false": errors 1`] = `Array []`; - -exports[`emit option should work with locals when emit option is "false": warnings 1`] = `Array []`; - -exports[`emit option should work without emit option: assets 1`] = ` -Array [ - "main.bundle.js", - "main.css", - "react.svg", -] -`; - -exports[`emit option should work without emit option: errors 1`] = `Array []`; - -exports[`emit option should work without emit option: warnings 1`] = `Array []`; diff --git a/test/__snapshots__/insert-option.test.js.snap.webpack4 b/test/__snapshots__/insert-option.test.js.snap similarity index 100% rename from test/__snapshots__/insert-option.test.js.snap.webpack4 rename to test/__snapshots__/insert-option.test.js.snap diff --git a/test/__snapshots__/insert-option.test.js.snap.webpack5 b/test/__snapshots__/insert-option.test.js.snap.webpack5 deleted file mode 100644 index 1e8530eb..00000000 --- a/test/__snapshots__/insert-option.test.js.snap.webpack5 +++ /dev/null @@ -1,55 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`insert option should work when insert option is function: DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`insert option should work when insert option is function: errors 1`] = `Array []`; - -exports[`insert option should work when insert option is function: warnings 1`] = `Array []`; - -exports[`insert option should work when insert option is string: DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`insert option should work when insert option is string: errors 1`] = `Array []`; - -exports[`insert option should work when insert option is string: warnings 1`] = `Array []`; - -exports[`insert option should work without insert option: DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`insert option should work without insert option: errors 1`] = `Array []`; - -exports[`insert option should work without insert option: warnings 1`] = `Array []`; diff --git a/test/__snapshots__/linkTag-option.test.js.snap.webpack4 b/test/__snapshots__/linkTag-option.test.js.snap similarity index 100% rename from test/__snapshots__/linkTag-option.test.js.snap.webpack4 rename to test/__snapshots__/linkTag-option.test.js.snap diff --git a/test/__snapshots__/linkTag-option.test.js.snap.webpack5 b/test/__snapshots__/linkTag-option.test.js.snap.webpack5 deleted file mode 100644 index 8a4e62d9..00000000 --- a/test/__snapshots__/linkTag-option.test.js.snap.webpack5 +++ /dev/null @@ -1,55 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`linkType option should work when linkType option is "false": DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`linkType option should work when linkType option is "false": errors 1`] = `Array []`; - -exports[`linkType option should work when linkType option is "false": warnings 1`] = `Array []`; - -exports[`linkType option should work when linkType option is "text/css": DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`linkType option should work when linkType option is "text/css": errors 1`] = `Array []`; - -exports[`linkType option should work when linkType option is "text/css": warnings 1`] = `Array []`; - -exports[`linkType option should work without linkType option: DOM 1`] = ` -" - style-loader test - - - -

Body

-
- - - -" -`; - -exports[`linkType option should work without linkType option: errors 1`] = `Array []`; - -exports[`linkType option should work without linkType option: warnings 1`] = `Array []`; diff --git a/test/__snapshots__/validate-loader-options.test.js.snap.webpack4 b/test/__snapshots__/validate-loader-options.test.js.snap similarity index 100% rename from test/__snapshots__/validate-loader-options.test.js.snap.webpack4 rename to test/__snapshots__/validate-loader-options.test.js.snap diff --git a/test/__snapshots__/validate-loader-options.test.js.snap.webpack5 b/test/__snapshots__/validate-loader-options.test.js.snap.webpack5 deleted file mode 100644 index 3ef75319..00000000 --- a/test/__snapshots__/validate-loader-options.test.js.snap.webpack5 +++ /dev/null @@ -1,63 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`validate options should throw an error on the "esModule" option with "1" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options.esModule should be a boolean." -`; - -exports[`validate options should throw an error on the "publicPath" option with "true" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options.publicPath should be one of these: - string | function - Details: - * options.publicPath should be a string. - * options.publicPath should be an instance of function." -`; - -exports[`validate options should throw an error on the "unknown" option with "/test/" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "[]" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "{"foo":"bar"}" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "{}" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "1" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "false" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "test" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "true" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { publicPath?, emit?, esModule?, layer? }" -`; diff --git a/test/__snapshots__/validate-plugin-options.test.js.snap.webpack4 b/test/__snapshots__/validate-plugin-options.test.js.snap similarity index 100% rename from test/__snapshots__/validate-plugin-options.test.js.snap.webpack4 rename to test/__snapshots__/validate-plugin-options.test.js.snap diff --git a/test/__snapshots__/validate-plugin-options.test.js.snap.webpack5 b/test/__snapshots__/validate-plugin-options.test.js.snap.webpack5 deleted file mode 100644 index 7da02d24..00000000 --- a/test/__snapshots__/validate-plugin-options.test.js.snap.webpack5 +++ /dev/null @@ -1,145 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`validate options should throw an error on the "attributes" option with "true" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.attributes should be an object: - object { … } - -> Adds custom attributes to tag (https://github.com/webpack-contrib/mini-css-extract-plugin#attributes)." -`; - -exports[`validate options should throw an error on the "chunkFilename" option with "true" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.chunkFilename should be one of these: - string | function - Details: - * options.chunkFilename should be a string. - * options.chunkFilename should be an instance of function." -`; - -exports[`validate options should throw an error on the "filename" option with "true" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.filename should be one of these: - string | function - Details: - * options.filename should be a string. - * options.filename should be an instance of function." -`; - -exports[`validate options should throw an error on the "ignoreOrder" option with "1" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.ignoreOrder should be a boolean." -`; - -exports[`validate options should throw an error on the "insert" option with "{}" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.insert should be one of these: - string | function - -> Inserts \`\` at the given position (https://github.com/webpack-contrib/mini-css-extract-plugin#insert). - Details: - * options.insert should be a string. - * options.insert should be an instance of function." -`; - -exports[`validate options should throw an error on the "insert" option with "1" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.insert should be one of these: - string | function - -> Inserts \`\` at the given position (https://github.com/webpack-contrib/mini-css-extract-plugin#insert). - Details: - * options.insert should be a string. - * options.insert should be an instance of function." -`; - -exports[`validate options should throw an error on the "insert" option with "true" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.insert should be one of these: - string | function - -> Inserts \`\` at the given position (https://github.com/webpack-contrib/mini-css-extract-plugin#insert). - Details: - * options.insert should be a string. - * options.insert should be an instance of function." -`; - -exports[`validate options should throw an error on the "linkType" option with "[]" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.linkType should be one of these: - \\"text/css\\" | boolean - Details: - * options.linkType should be \\"text/css\\". - * options.linkType should be a boolean." -`; - -exports[`validate options should throw an error on the "linkType" option with "{}" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.linkType should be one of these: - \\"text/css\\" | boolean - Details: - * options.linkType should be \\"text/css\\". - * options.linkType should be a boolean." -`; - -exports[`validate options should throw an error on the "linkType" option with "1" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.linkType should be one of these: - \\"text/css\\" | boolean - Details: - * options.linkType should be \\"text/css\\". - * options.linkType should be a boolean." -`; - -exports[`validate options should throw an error on the "linkType" option with "invalid/type" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options.linkType should be one of these: - \\"text/css\\" | boolean - Details: - * options.linkType should be \\"text/css\\". - * options.linkType should be a boolean." -`; - -exports[`validate options should throw an error on the "unknown" option with "/test/" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "[]" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "{"foo":"bar"}" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "{}" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "1" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "false" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "test" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; - -exports[`validate options should throw an error on the "unknown" option with "true" value 1`] = ` -"Invalid options object. Mini CSS Extract Plugin has been initialized using an options object that does not match the API schema. - - options has an unknown property 'unknown'. These properties are valid: - object { filename?, chunkFilename?, experimentalUseImportModule?, ignoreOrder?, insert?, attributes?, linkType? }" -`; diff --git a/test/cases/auxiliaryAssets/test.filter.js b/test/cases/auxiliaryAssets/test.filter.js index 20341d78..d04b7de0 100644 --- a/test/cases/auxiliaryAssets/test.filter.js +++ b/test/cases/auxiliaryAssets/test.filter.js @@ -1,4 +1 @@ -const webpack = require('webpack'); - -module.exports = () => - webpack.version[0] !== '4' && !process.env.EXPERIMENTAL_USE_IMPORT_MODULE; +module.exports = () => !process.env.EXPERIMENTAL_USE_IMPORT_MODULE; diff --git a/test/cases/chunkFilename-as-function/expected/webpack-4/1.async.css b/test/cases/chunkFilename-as-function/expected/webpack-4/1.async.css deleted file mode 100644 index e665100a..00000000 --- a/test/cases/chunkFilename-as-function/expected/webpack-4/1.async.css +++ /dev/null @@ -1,4 +0,0 @@ -.async { - color: red; -} - diff --git a/test/cases/chunkFilename-as-function/expected/webpack-4/main.css b/test/cases/chunkFilename-as-function/expected/webpack-4/main.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/chunkFilename-as-function/expected/webpack-4/main.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/chunkFilename/expected/webpack-4/1.async.css b/test/cases/chunkFilename/expected/webpack-4/1.async.css deleted file mode 100644 index e665100a..00000000 --- a/test/cases/chunkFilename/expected/webpack-4/1.async.css +++ /dev/null @@ -1,4 +0,0 @@ -.async { - color: red; -} - diff --git a/test/cases/chunkFilename/expected/webpack-4/main.css b/test/cases/chunkFilename/expected/webpack-4/main.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/chunkFilename/expected/webpack-4/main.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/contenthash-multiple-entries/expected/webpack-4/96236f7f51b351aabd20.css b/test/cases/contenthash-multiple-entries/expected/webpack-4/96236f7f51b351aabd20.css deleted file mode 100644 index 95d70a8e..00000000 --- a/test/cases/contenthash-multiple-entries/expected/webpack-4/96236f7f51b351aabd20.css +++ /dev/null @@ -1,4 +0,0 @@ -.styleA { - background: red; -} - diff --git a/test/cases/contenthash-multiple-entries/expected/webpack-4/f22bc5a793a5a86ad253.css b/test/cases/contenthash-multiple-entries/expected/webpack-4/f22bc5a793a5a86ad253.css deleted file mode 100644 index c6856116..00000000 --- a/test/cases/contenthash-multiple-entries/expected/webpack-4/f22bc5a793a5a86ad253.css +++ /dev/null @@ -1,8 +0,0 @@ -.styleA { - background: red; -} - -.styleB { - background: blue; -} - diff --git a/test/cases/contenthash/expected/webpack-4/1.main.c4d90d38e7a606ae4d4c.css b/test/cases/contenthash/expected/webpack-4/1.main.c4d90d38e7a606ae4d4c.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/contenthash/expected/webpack-4/1.main.c4d90d38e7a606ae4d4c.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/contenthash/expected/webpack-4/2.main.64d1032b1547f22458a7.css b/test/cases/contenthash/expected/webpack-4/2.main.64d1032b1547f22458a7.css deleted file mode 100644 index ec3b88b5..00000000 --- a/test/cases/contenthash/expected/webpack-4/2.main.64d1032b1547f22458a7.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: green; -} - diff --git a/test/cases/devtool-source-map-from-loaders/expected/webpack-4/main.css b/test/cases/devtool-source-map-from-loaders/expected/webpack-4/main.css deleted file mode 100644 index 8f8cf968..00000000 --- a/test/cases/devtool-source-map-from-loaders/expected/webpack-4/main.css +++ /dev/null @@ -1,6 +0,0 @@ -body { - background: red; -} - - -/*# sourceMappingURL=main.css.map*/ \ No newline at end of file diff --git a/test/cases/devtool-source-map-from-loaders/expected/webpack-4/main.css.map b/test/cases/devtool-source-map-from-loaders/expected/webpack-4/main.css.map deleted file mode 100644 index bb767168..00000000 --- a/test/cases/devtool-source-map-from-loaders/expected/webpack-4/main.css.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["webpack:///./style.css"],"names":[],"mappings":"AAAA;EACE,eAAe;AACjB","file":"main.css","sourcesContent":["body {\n background: red;\n}\n"],"sourceRoot":""} \ No newline at end of file diff --git a/test/cases/devtool-source-map-no-source-maps-from-loaders/expected/webpack-4/main.css b/test/cases/devtool-source-map-no-source-maps-from-loaders/expected/webpack-4/main.css deleted file mode 100644 index 8f8cf968..00000000 --- a/test/cases/devtool-source-map-no-source-maps-from-loaders/expected/webpack-4/main.css +++ /dev/null @@ -1,6 +0,0 @@ -body { - background: red; -} - - -/*# sourceMappingURL=main.css.map*/ \ No newline at end of file diff --git a/test/cases/devtool-source-map-no-source-maps-from-loaders/expected/webpack-4/main.css.map b/test/cases/devtool-source-map-no-source-maps-from-loaders/expected/webpack-4/main.css.map deleted file mode 100644 index b350621d..00000000 --- a/test/cases/devtool-source-map-no-source-maps-from-loaders/expected/webpack-4/main.css.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":[],"names":[],"mappings":"","file":"main.css","sourceRoot":""} \ No newline at end of file diff --git a/test/cases/es-module-concatenation-modules/expected/webpack-4/main.css b/test/cases/es-module-concatenation-modules/expected/webpack-4/main.css deleted file mode 100644 index 414d12e5..00000000 --- a/test/cases/es-module-concatenation-modules/expected/webpack-4/main.css +++ /dev/null @@ -1,12 +0,0 @@ -.foo__a { - background: red; -} - -.foo__b { - background: green; -} - -.foo__c { - background: blue; -} - diff --git a/test/cases/es-module-concatenation-modules/expected/webpack-4/main.js b/test/cases/es-module-concatenation-modules/expected/webpack-4/main.js deleted file mode 100644 index 0552cd62..00000000 --- a/test/cases/es-module-concatenation-modules/expected/webpack-4/main.js +++ /dev/null @@ -1,141 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ c; }); -__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ a_namespaceObject; }); -__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ b_namespaceObject; }); - -// NAMESPACE OBJECT: ./a.css -var a_namespaceObject = {}; -__webpack_require__.r(a_namespaceObject); -__webpack_require__.d(a_namespaceObject, "a", function() { return a; }); - -// NAMESPACE OBJECT: ./b.css -var b_namespaceObject = {}; -__webpack_require__.r(b_namespaceObject); -__webpack_require__.d(b_namespaceObject, "b", function() { return b; }); - -// NAMESPACE OBJECT: ./index.js -var index_namespaceObject = {}; -__webpack_require__.r(index_namespaceObject); -__webpack_require__.d(index_namespaceObject, "c", function() { return c; }); -__webpack_require__.d(index_namespaceObject, "a", function() { return a_namespaceObject; }); -__webpack_require__.d(index_namespaceObject, "b", function() { return b_namespaceObject; }); - -// CONCATENATED MODULE: ./a.css -// extracted by mini-css-extract-plugin -var a = "foo__a"; -// CONCATENATED MODULE: ./b.css -// extracted by mini-css-extract-plugin -var b = "foo__b"; -// CONCATENATED MODULE: ./c.css -// extracted by mini-css-extract-plugin -var c = "foo__c"; -// CONCATENATED MODULE: ./index.js -/* eslint-disable import/no-namespace */ - - - - - - - - -// eslint-disable-next-line no-console -console.log(index_namespaceObject); - - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/test/cases/es-module-concatenation/expected/webpack-4/main.css b/test/cases/es-module-concatenation/expected/webpack-4/main.css deleted file mode 100644 index a5728976..00000000 --- a/test/cases/es-module-concatenation/expected/webpack-4/main.css +++ /dev/null @@ -1,12 +0,0 @@ -.a { - background: red; -} - -.b { - background: green; -} - -.c { - background: blue; -} - diff --git a/test/cases/es-module-concatenation/expected/webpack-4/main.js b/test/cases/es-module-concatenation/expected/webpack-4/main.js deleted file mode 100644 index 001ba1de..00000000 --- a/test/cases/es-module-concatenation/expected/webpack-4/main.js +++ /dev/null @@ -1,111 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// CONCATENATED MODULE: ./a.css -// extracted by mini-css-extract-plugin - -// CONCATENATED MODULE: ./b.css -// extracted by mini-css-extract-plugin - -// CONCATENATED MODULE: ./c.css -// extracted by mini-css-extract-plugin - -// CONCATENATED MODULE: ./index.js - - - - - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/test/cases/es-named-export/expected/webpack-4/main.css b/test/cases/es-named-export/expected/webpack-4/main.css deleted file mode 100644 index aa9b1569..00000000 --- a/test/cases/es-named-export/expected/webpack-4/main.css +++ /dev/null @@ -1,12 +0,0 @@ -.foo__style__a-class { - background: red; -} - -.foo__style__b__class { - color: green; -} - -.foo__style__cClass { - color: blue; -} - diff --git a/test/cases/es-named-export/expected/webpack-4/main.js b/test/cases/es-named-export/expected/webpack-4/main.js deleted file mode 100644 index 9386c187..00000000 --- a/test/cases/es-named-export/expected/webpack-4/main.js +++ /dev/null @@ -1,115 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony import */ var _style_css__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); - - -// eslint-disable-next-line no-console -console.log({ css: _style_css__WEBPACK_IMPORTED_MODULE_0__["default"], aClass: _style_css__WEBPACK_IMPORTED_MODULE_0__["aClass"], bClass: _style_css__WEBPACK_IMPORTED_MODULE_0__["bClass"], cClass: _style_css__WEBPACK_IMPORTED_MODULE_0__["cClass"] }); - - -/***/ }), -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "aClass", function() { return aClass; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bClass", function() { return bClass; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "cClass", function() { return cClass; }); -// extracted by mini-css-extract-plugin -var aClass = "foo__style__a-class"; -var bClass = "foo__style__b__class"; -var cClass = "foo__style__cClass"; - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/test/cases/filename-without-template/expected/webpack-4/1.main.css b/test/cases/filename-without-template/expected/webpack-4/1.main.css deleted file mode 100644 index e665100a..00000000 --- a/test/cases/filename-without-template/expected/webpack-4/1.main.css +++ /dev/null @@ -1,4 +0,0 @@ -.async { - color: red; -} - diff --git a/test/cases/filename-without-template/expected/webpack-4/main.css b/test/cases/filename-without-template/expected/webpack-4/main.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/filename-without-template/expected/webpack-4/main.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/hmr/expected/webpack-4/main.css b/test/cases/hmr/expected/webpack-4/main.css deleted file mode 100644 index 6f77cc07..00000000 --- a/test/cases/hmr/expected/webpack-4/main.css +++ /dev/null @@ -1,24 +0,0 @@ -@import url(https://some/other/external/css); -@import url(https://some/external/css); -body { - background: red; -} - -.c { - background: red; -} - -.c { - color: yellow; -} - -.b { - background: red; -} - -.b { - color: yellow; -} - - - diff --git a/test/cases/hmr/expected/webpack-4/main.js b/test/cases/hmr/expected/webpack-4/main.js deleted file mode 100644 index 3ddc13a2..00000000 --- a/test/cases/hmr/expected/webpack-4/main.js +++ /dev/null @@ -1,1167 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ function hotDisposeChunk(chunkId) { -/******/ delete installedChunks[chunkId]; -/******/ } -/******/ var parentHotUpdateCallback = window["webpackHotUpdate"]; -/******/ window["webpackHotUpdate"] = // eslint-disable-next-line no-unused-vars -/******/ function webpackHotUpdateCallback(chunkId, moreModules) { -/******/ hotAddUpdateChunk(chunkId, moreModules); -/******/ if (parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); -/******/ } ; -/******/ -/******/ // eslint-disable-next-line no-unused-vars -/******/ function hotDownloadUpdateChunk(chunkId) { -/******/ var script = document.createElement("script"); -/******/ script.charset = "utf-8"; -/******/ script.src = __webpack_require__.p + "" + chunkId + "." + hotCurrentHash + ".hot-update.js"; -/******/ if (null) script.crossOrigin = null; -/******/ document.head.appendChild(script); -/******/ } -/******/ -/******/ // eslint-disable-next-line no-unused-vars -/******/ function hotDownloadManifest(requestTimeout) { -/******/ requestTimeout = requestTimeout || 10000; -/******/ return new Promise(function(resolve, reject) { -/******/ if (typeof XMLHttpRequest === "undefined") { -/******/ return reject(new Error("No browser support")); -/******/ } -/******/ try { -/******/ var request = new XMLHttpRequest(); -/******/ var requestPath = __webpack_require__.p + "" + hotCurrentHash + ".hot-update.json"; -/******/ request.open("GET", requestPath, true); -/******/ request.timeout = requestTimeout; -/******/ request.send(null); -/******/ } catch (err) { -/******/ return reject(err); -/******/ } -/******/ request.onreadystatechange = function() { -/******/ if (request.readyState !== 4) return; -/******/ if (request.status === 0) { -/******/ // timeout -/******/ reject( -/******/ new Error("Manifest request to " + requestPath + " timed out.") -/******/ ); -/******/ } else if (request.status === 404) { -/******/ // no update available -/******/ resolve(); -/******/ } else if (request.status !== 200 && request.status !== 304) { -/******/ // other failure -/******/ reject(new Error("Manifest request to " + requestPath + " failed.")); -/******/ } else { -/******/ // success -/******/ try { -/******/ var update = JSON.parse(request.responseText); -/******/ } catch (e) { -/******/ reject(e); -/******/ return; -/******/ } -/******/ resolve(update); -/******/ } -/******/ }; -/******/ }); -/******/ } -/******/ -/******/ var hotApplyOnUpdate = true; -/******/ // eslint-disable-next-line no-unused-vars -/******/ var hotCurrentHash = "xxxxxxxxxxxxxxxxxxxx"; -/******/ var hotRequestTimeout = 10000; -/******/ var hotCurrentModuleData = {}; -/******/ var hotCurrentChildModule; -/******/ // eslint-disable-next-line no-unused-vars -/******/ var hotCurrentParents = []; -/******/ // eslint-disable-next-line no-unused-vars -/******/ var hotCurrentParentsTemp = []; -/******/ -/******/ // eslint-disable-next-line no-unused-vars -/******/ function hotCreateRequire(moduleId) { -/******/ var me = installedModules[moduleId]; -/******/ if (!me) return __webpack_require__; -/******/ var fn = function(request) { -/******/ if (me.hot.active) { -/******/ if (installedModules[request]) { -/******/ if (installedModules[request].parents.indexOf(moduleId) === -1) { -/******/ installedModules[request].parents.push(moduleId); -/******/ } -/******/ } else { -/******/ hotCurrentParents = [moduleId]; -/******/ hotCurrentChildModule = request; -/******/ } -/******/ if (me.children.indexOf(request) === -1) { -/******/ me.children.push(request); -/******/ } -/******/ } else { -/******/ console.warn( -/******/ "[HMR] unexpected require(" + -/******/ request + -/******/ ") from disposed module " + -/******/ moduleId -/******/ ); -/******/ hotCurrentParents = []; -/******/ } -/******/ return __webpack_require__(request); -/******/ }; -/******/ var ObjectFactory = function ObjectFactory(name) { -/******/ return { -/******/ configurable: true, -/******/ enumerable: true, -/******/ get: function() { -/******/ return __webpack_require__[name]; -/******/ }, -/******/ set: function(value) { -/******/ __webpack_require__[name] = value; -/******/ } -/******/ }; -/******/ }; -/******/ for (var name in __webpack_require__) { -/******/ if ( -/******/ Object.prototype.hasOwnProperty.call(__webpack_require__, name) && -/******/ name !== "e" && -/******/ name !== "t" -/******/ ) { -/******/ Object.defineProperty(fn, name, ObjectFactory(name)); -/******/ } -/******/ } -/******/ fn.e = function(chunkId) { -/******/ if (hotStatus === "ready") hotSetStatus("prepare"); -/******/ hotChunksLoading++; -/******/ return __webpack_require__.e(chunkId).then(finishChunkLoading, function(err) { -/******/ finishChunkLoading(); -/******/ throw err; -/******/ }); -/******/ -/******/ function finishChunkLoading() { -/******/ hotChunksLoading--; -/******/ if (hotStatus === "prepare") { -/******/ if (!hotWaitingFilesMap[chunkId]) { -/******/ hotEnsureUpdateChunk(chunkId); -/******/ } -/******/ if (hotChunksLoading === 0 && hotWaitingFiles === 0) { -/******/ hotUpdateDownloaded(); -/******/ } -/******/ } -/******/ } -/******/ }; -/******/ fn.t = function(value, mode) { -/******/ if (mode & 1) value = fn(value); -/******/ return __webpack_require__.t(value, mode & ~1); -/******/ }; -/******/ return fn; -/******/ } -/******/ -/******/ // eslint-disable-next-line no-unused-vars -/******/ function hotCreateModule(moduleId) { -/******/ var hot = { -/******/ // private stuff -/******/ _acceptedDependencies: {}, -/******/ _declinedDependencies: {}, -/******/ _selfAccepted: false, -/******/ _selfDeclined: false, -/******/ _selfInvalidated: false, -/******/ _disposeHandlers: [], -/******/ _main: hotCurrentChildModule !== moduleId, -/******/ -/******/ // Module API -/******/ active: true, -/******/ accept: function(dep, callback) { -/******/ if (dep === undefined) hot._selfAccepted = true; -/******/ else if (typeof dep === "function") hot._selfAccepted = dep; -/******/ else if (typeof dep === "object") -/******/ for (var i = 0; i < dep.length; i++) -/******/ hot._acceptedDependencies[dep[i]] = callback || function() {}; -/******/ else hot._acceptedDependencies[dep] = callback || function() {}; -/******/ }, -/******/ decline: function(dep) { -/******/ if (dep === undefined) hot._selfDeclined = true; -/******/ else if (typeof dep === "object") -/******/ for (var i = 0; i < dep.length; i++) -/******/ hot._declinedDependencies[dep[i]] = true; -/******/ else hot._declinedDependencies[dep] = true; -/******/ }, -/******/ dispose: function(callback) { -/******/ hot._disposeHandlers.push(callback); -/******/ }, -/******/ addDisposeHandler: function(callback) { -/******/ hot._disposeHandlers.push(callback); -/******/ }, -/******/ removeDisposeHandler: function(callback) { -/******/ var idx = hot._disposeHandlers.indexOf(callback); -/******/ if (idx >= 0) hot._disposeHandlers.splice(idx, 1); -/******/ }, -/******/ invalidate: function() { -/******/ this._selfInvalidated = true; -/******/ switch (hotStatus) { -/******/ case "idle": -/******/ hotUpdate = {}; -/******/ hotUpdate[moduleId] = modules[moduleId]; -/******/ hotSetStatus("ready"); -/******/ break; -/******/ case "ready": -/******/ hotApplyInvalidatedModule(moduleId); -/******/ break; -/******/ case "prepare": -/******/ case "check": -/******/ case "dispose": -/******/ case "apply": -/******/ (hotQueuedInvalidatedModules = -/******/ hotQueuedInvalidatedModules || []).push(moduleId); -/******/ break; -/******/ default: -/******/ // ignore requests in error states -/******/ break; -/******/ } -/******/ }, -/******/ -/******/ // Management API -/******/ check: hotCheck, -/******/ apply: hotApply, -/******/ status: function(l) { -/******/ if (!l) return hotStatus; -/******/ hotStatusHandlers.push(l); -/******/ }, -/******/ addStatusHandler: function(l) { -/******/ hotStatusHandlers.push(l); -/******/ }, -/******/ removeStatusHandler: function(l) { -/******/ var idx = hotStatusHandlers.indexOf(l); -/******/ if (idx >= 0) hotStatusHandlers.splice(idx, 1); -/******/ }, -/******/ -/******/ //inherit from previous dispose call -/******/ data: hotCurrentModuleData[moduleId] -/******/ }; -/******/ hotCurrentChildModule = undefined; -/******/ return hot; -/******/ } -/******/ -/******/ var hotStatusHandlers = []; -/******/ var hotStatus = "idle"; -/******/ -/******/ function hotSetStatus(newStatus) { -/******/ hotStatus = newStatus; -/******/ for (var i = 0; i < hotStatusHandlers.length; i++) -/******/ hotStatusHandlers[i].call(null, newStatus); -/******/ } -/******/ -/******/ // while downloading -/******/ var hotWaitingFiles = 0; -/******/ var hotChunksLoading = 0; -/******/ var hotWaitingFilesMap = {}; -/******/ var hotRequestedFilesMap = {}; -/******/ var hotAvailableFilesMap = {}; -/******/ var hotDeferred; -/******/ -/******/ // The update info -/******/ var hotUpdate, hotUpdateNewHash, hotQueuedInvalidatedModules; -/******/ -/******/ function toModuleId(id) { -/******/ var isNumber = +id + "" === id; -/******/ return isNumber ? +id : id; -/******/ } -/******/ -/******/ function hotCheck(apply) { -/******/ if (hotStatus !== "idle") { -/******/ throw new Error("check() is only allowed in idle status"); -/******/ } -/******/ hotApplyOnUpdate = apply; -/******/ hotSetStatus("check"); -/******/ return hotDownloadManifest(hotRequestTimeout).then(function(update) { -/******/ if (!update) { -/******/ hotSetStatus(hotApplyInvalidatedModules() ? "ready" : "idle"); -/******/ return null; -/******/ } -/******/ hotRequestedFilesMap = {}; -/******/ hotWaitingFilesMap = {}; -/******/ hotAvailableFilesMap = update.c; -/******/ hotUpdateNewHash = update.h; -/******/ -/******/ hotSetStatus("prepare"); -/******/ var promise = new Promise(function(resolve, reject) { -/******/ hotDeferred = { -/******/ resolve: resolve, -/******/ reject: reject -/******/ }; -/******/ }); -/******/ hotUpdate = {}; -/******/ var chunkId = 0; -/******/ // eslint-disable-next-line no-lone-blocks -/******/ { -/******/ hotEnsureUpdateChunk(chunkId); -/******/ } -/******/ if ( -/******/ hotStatus === "prepare" && -/******/ hotChunksLoading === 0 && -/******/ hotWaitingFiles === 0 -/******/ ) { -/******/ hotUpdateDownloaded(); -/******/ } -/******/ return promise; -/******/ }); -/******/ } -/******/ -/******/ // eslint-disable-next-line no-unused-vars -/******/ function hotAddUpdateChunk(chunkId, moreModules) { -/******/ if (!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId]) -/******/ return; -/******/ hotRequestedFilesMap[chunkId] = false; -/******/ for (var moduleId in moreModules) { -/******/ if (Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { -/******/ hotUpdate[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if (--hotWaitingFiles === 0 && hotChunksLoading === 0) { -/******/ hotUpdateDownloaded(); -/******/ } -/******/ } -/******/ -/******/ function hotEnsureUpdateChunk(chunkId) { -/******/ if (!hotAvailableFilesMap[chunkId]) { -/******/ hotWaitingFilesMap[chunkId] = true; -/******/ } else { -/******/ hotRequestedFilesMap[chunkId] = true; -/******/ hotWaitingFiles++; -/******/ hotDownloadUpdateChunk(chunkId); -/******/ } -/******/ } -/******/ -/******/ function hotUpdateDownloaded() { -/******/ hotSetStatus("ready"); -/******/ var deferred = hotDeferred; -/******/ hotDeferred = null; -/******/ if (!deferred) return; -/******/ if (hotApplyOnUpdate) { -/******/ // Wrap deferred object in Promise to mark it as a well-handled Promise to -/******/ // avoid triggering uncaught exception warning in Chrome. -/******/ // See https://bugs.chromium.org/p/chromium/issues/detail?id=465666 -/******/ Promise.resolve() -/******/ .then(function() { -/******/ return hotApply(hotApplyOnUpdate); -/******/ }) -/******/ .then( -/******/ function(result) { -/******/ deferred.resolve(result); -/******/ }, -/******/ function(err) { -/******/ deferred.reject(err); -/******/ } -/******/ ); -/******/ } else { -/******/ var outdatedModules = []; -/******/ for (var id in hotUpdate) { -/******/ if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { -/******/ outdatedModules.push(toModuleId(id)); -/******/ } -/******/ } -/******/ deferred.resolve(outdatedModules); -/******/ } -/******/ } -/******/ -/******/ function hotApply(options) { -/******/ if (hotStatus !== "ready") -/******/ throw new Error("apply() is only allowed in ready status"); -/******/ options = options || {}; -/******/ return hotApplyInternal(options); -/******/ } -/******/ -/******/ function hotApplyInternal(options) { -/******/ hotApplyInvalidatedModules(); -/******/ -/******/ var cb; -/******/ var i; -/******/ var j; -/******/ var module; -/******/ var moduleId; -/******/ -/******/ function getAffectedStuff(updateModuleId) { -/******/ var outdatedModules = [updateModuleId]; -/******/ var outdatedDependencies = {}; -/******/ -/******/ var queue = outdatedModules.map(function(id) { -/******/ return { -/******/ chain: [id], -/******/ id: id -/******/ }; -/******/ }); -/******/ while (queue.length > 0) { -/******/ var queueItem = queue.pop(); -/******/ var moduleId = queueItem.id; -/******/ var chain = queueItem.chain; -/******/ module = installedModules[moduleId]; -/******/ if ( -/******/ !module || -/******/ (module.hot._selfAccepted && !module.hot._selfInvalidated) -/******/ ) -/******/ continue; -/******/ if (module.hot._selfDeclined) { -/******/ return { -/******/ type: "self-declined", -/******/ chain: chain, -/******/ moduleId: moduleId -/******/ }; -/******/ } -/******/ if (module.hot._main) { -/******/ return { -/******/ type: "unaccepted", -/******/ chain: chain, -/******/ moduleId: moduleId -/******/ }; -/******/ } -/******/ for (var i = 0; i < module.parents.length; i++) { -/******/ var parentId = module.parents[i]; -/******/ var parent = installedModules[parentId]; -/******/ if (!parent) continue; -/******/ if (parent.hot._declinedDependencies[moduleId]) { -/******/ return { -/******/ type: "declined", -/******/ chain: chain.concat([parentId]), -/******/ moduleId: moduleId, -/******/ parentId: parentId -/******/ }; -/******/ } -/******/ if (outdatedModules.indexOf(parentId) !== -1) continue; -/******/ if (parent.hot._acceptedDependencies[moduleId]) { -/******/ if (!outdatedDependencies[parentId]) -/******/ outdatedDependencies[parentId] = []; -/******/ addAllToSet(outdatedDependencies[parentId], [moduleId]); -/******/ continue; -/******/ } -/******/ delete outdatedDependencies[parentId]; -/******/ outdatedModules.push(parentId); -/******/ queue.push({ -/******/ chain: chain.concat([parentId]), -/******/ id: parentId -/******/ }); -/******/ } -/******/ } -/******/ -/******/ return { -/******/ type: "accepted", -/******/ moduleId: updateModuleId, -/******/ outdatedModules: outdatedModules, -/******/ outdatedDependencies: outdatedDependencies -/******/ }; -/******/ } -/******/ -/******/ function addAllToSet(a, b) { -/******/ for (var i = 0; i < b.length; i++) { -/******/ var item = b[i]; -/******/ if (a.indexOf(item) === -1) a.push(item); -/******/ } -/******/ } -/******/ -/******/ // at begin all updates modules are outdated -/******/ // the "outdated" status can propagate to parents if they don't accept the children -/******/ var outdatedDependencies = {}; -/******/ var outdatedModules = []; -/******/ var appliedUpdate = {}; -/******/ -/******/ var warnUnexpectedRequire = function warnUnexpectedRequire() { -/******/ console.warn( -/******/ "[HMR] unexpected require(" + result.moduleId + ") to disposed module" -/******/ ); -/******/ }; -/******/ -/******/ for (var id in hotUpdate) { -/******/ if (Object.prototype.hasOwnProperty.call(hotUpdate, id)) { -/******/ moduleId = toModuleId(id); -/******/ /** @type {TODO} */ -/******/ var result; -/******/ if (hotUpdate[id]) { -/******/ result = getAffectedStuff(moduleId); -/******/ } else { -/******/ result = { -/******/ type: "disposed", -/******/ moduleId: id -/******/ }; -/******/ } -/******/ /** @type {Error|false} */ -/******/ var abortError = false; -/******/ var doApply = false; -/******/ var doDispose = false; -/******/ var chainInfo = ""; -/******/ if (result.chain) { -/******/ chainInfo = "\nUpdate propagation: " + result.chain.join(" -> "); -/******/ } -/******/ switch (result.type) { -/******/ case "self-declined": -/******/ if (options.onDeclined) options.onDeclined(result); -/******/ if (!options.ignoreDeclined) -/******/ abortError = new Error( -/******/ "Aborted because of self decline: " + -/******/ result.moduleId + -/******/ chainInfo -/******/ ); -/******/ break; -/******/ case "declined": -/******/ if (options.onDeclined) options.onDeclined(result); -/******/ if (!options.ignoreDeclined) -/******/ abortError = new Error( -/******/ "Aborted because of declined dependency: " + -/******/ result.moduleId + -/******/ " in " + -/******/ result.parentId + -/******/ chainInfo -/******/ ); -/******/ break; -/******/ case "unaccepted": -/******/ if (options.onUnaccepted) options.onUnaccepted(result); -/******/ if (!options.ignoreUnaccepted) -/******/ abortError = new Error( -/******/ "Aborted because " + moduleId + " is not accepted" + chainInfo -/******/ ); -/******/ break; -/******/ case "accepted": -/******/ if (options.onAccepted) options.onAccepted(result); -/******/ doApply = true; -/******/ break; -/******/ case "disposed": -/******/ if (options.onDisposed) options.onDisposed(result); -/******/ doDispose = true; -/******/ break; -/******/ default: -/******/ throw new Error("Unexception type " + result.type); -/******/ } -/******/ if (abortError) { -/******/ hotSetStatus("abort"); -/******/ return Promise.reject(abortError); -/******/ } -/******/ if (doApply) { -/******/ appliedUpdate[moduleId] = hotUpdate[moduleId]; -/******/ addAllToSet(outdatedModules, result.outdatedModules); -/******/ for (moduleId in result.outdatedDependencies) { -/******/ if ( -/******/ Object.prototype.hasOwnProperty.call( -/******/ result.outdatedDependencies, -/******/ moduleId -/******/ ) -/******/ ) { -/******/ if (!outdatedDependencies[moduleId]) -/******/ outdatedDependencies[moduleId] = []; -/******/ addAllToSet( -/******/ outdatedDependencies[moduleId], -/******/ result.outdatedDependencies[moduleId] -/******/ ); -/******/ } -/******/ } -/******/ } -/******/ if (doDispose) { -/******/ addAllToSet(outdatedModules, [result.moduleId]); -/******/ appliedUpdate[moduleId] = warnUnexpectedRequire; -/******/ } -/******/ } -/******/ } -/******/ -/******/ // Store self accepted outdated modules to require them later by the module system -/******/ var outdatedSelfAcceptedModules = []; -/******/ for (i = 0; i < outdatedModules.length; i++) { -/******/ moduleId = outdatedModules[i]; -/******/ if ( -/******/ installedModules[moduleId] && -/******/ installedModules[moduleId].hot._selfAccepted && -/******/ // removed self-accepted modules should not be required -/******/ appliedUpdate[moduleId] !== warnUnexpectedRequire && -/******/ // when called invalidate self-accepting is not possible -/******/ !installedModules[moduleId].hot._selfInvalidated -/******/ ) { -/******/ outdatedSelfAcceptedModules.push({ -/******/ module: moduleId, -/******/ parents: installedModules[moduleId].parents.slice(), -/******/ errorHandler: installedModules[moduleId].hot._selfAccepted -/******/ }); -/******/ } -/******/ } -/******/ -/******/ // Now in "dispose" phase -/******/ hotSetStatus("dispose"); -/******/ Object.keys(hotAvailableFilesMap).forEach(function(chunkId) { -/******/ if (hotAvailableFilesMap[chunkId] === false) { -/******/ hotDisposeChunk(chunkId); -/******/ } -/******/ }); -/******/ -/******/ var idx; -/******/ var queue = outdatedModules.slice(); -/******/ while (queue.length > 0) { -/******/ moduleId = queue.pop(); -/******/ module = installedModules[moduleId]; -/******/ if (!module) continue; -/******/ -/******/ var data = {}; -/******/ -/******/ // Call dispose handlers -/******/ var disposeHandlers = module.hot._disposeHandlers; -/******/ for (j = 0; j < disposeHandlers.length; j++) { -/******/ cb = disposeHandlers[j]; -/******/ cb(data); -/******/ } -/******/ hotCurrentModuleData[moduleId] = data; -/******/ -/******/ // disable module (this disables requires from this module) -/******/ module.hot.active = false; -/******/ -/******/ // remove module from cache -/******/ delete installedModules[moduleId]; -/******/ -/******/ // when disposing there is no need to call dispose handler -/******/ delete outdatedDependencies[moduleId]; -/******/ -/******/ // remove "parents" references from all children -/******/ for (j = 0; j < module.children.length; j++) { -/******/ var child = installedModules[module.children[j]]; -/******/ if (!child) continue; -/******/ idx = child.parents.indexOf(moduleId); -/******/ if (idx >= 0) { -/******/ child.parents.splice(idx, 1); -/******/ } -/******/ } -/******/ } -/******/ -/******/ // remove outdated dependency from module children -/******/ var dependency; -/******/ var moduleOutdatedDependencies; -/******/ for (moduleId in outdatedDependencies) { -/******/ if ( -/******/ Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) -/******/ ) { -/******/ module = installedModules[moduleId]; -/******/ if (module) { -/******/ moduleOutdatedDependencies = outdatedDependencies[moduleId]; -/******/ for (j = 0; j < moduleOutdatedDependencies.length; j++) { -/******/ dependency = moduleOutdatedDependencies[j]; -/******/ idx = module.children.indexOf(dependency); -/******/ if (idx >= 0) module.children.splice(idx, 1); -/******/ } -/******/ } -/******/ } -/******/ } -/******/ -/******/ // Now in "apply" phase -/******/ hotSetStatus("apply"); -/******/ -/******/ if (hotUpdateNewHash !== undefined) { -/******/ hotCurrentHash = hotUpdateNewHash; -/******/ hotUpdateNewHash = undefined; -/******/ } -/******/ hotUpdate = undefined; -/******/ -/******/ // insert new code -/******/ for (moduleId in appliedUpdate) { -/******/ if (Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) { -/******/ modules[moduleId] = appliedUpdate[moduleId]; -/******/ } -/******/ } -/******/ -/******/ // call accept handlers -/******/ var error = null; -/******/ for (moduleId in outdatedDependencies) { -/******/ if ( -/******/ Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId) -/******/ ) { -/******/ module = installedModules[moduleId]; -/******/ if (module) { -/******/ moduleOutdatedDependencies = outdatedDependencies[moduleId]; -/******/ var callbacks = []; -/******/ for (i = 0; i < moduleOutdatedDependencies.length; i++) { -/******/ dependency = moduleOutdatedDependencies[i]; -/******/ cb = module.hot._acceptedDependencies[dependency]; -/******/ if (cb) { -/******/ if (callbacks.indexOf(cb) !== -1) continue; -/******/ callbacks.push(cb); -/******/ } -/******/ } -/******/ for (i = 0; i < callbacks.length; i++) { -/******/ cb = callbacks[i]; -/******/ try { -/******/ cb(moduleOutdatedDependencies); -/******/ } catch (err) { -/******/ if (options.onErrored) { -/******/ options.onErrored({ -/******/ type: "accept-errored", -/******/ moduleId: moduleId, -/******/ dependencyId: moduleOutdatedDependencies[i], -/******/ error: err -/******/ }); -/******/ } -/******/ if (!options.ignoreErrored) { -/******/ if (!error) error = err; -/******/ } -/******/ } -/******/ } -/******/ } -/******/ } -/******/ } -/******/ -/******/ // Load self accepted modules -/******/ for (i = 0; i < outdatedSelfAcceptedModules.length; i++) { -/******/ var item = outdatedSelfAcceptedModules[i]; -/******/ moduleId = item.module; -/******/ hotCurrentParents = item.parents; -/******/ hotCurrentChildModule = moduleId; -/******/ try { -/******/ __webpack_require__(moduleId); -/******/ } catch (err) { -/******/ if (typeof item.errorHandler === "function") { -/******/ try { -/******/ item.errorHandler(err); -/******/ } catch (err2) { -/******/ if (options.onErrored) { -/******/ options.onErrored({ -/******/ type: "self-accept-error-handler-errored", -/******/ moduleId: moduleId, -/******/ error: err2, -/******/ originalError: err -/******/ }); -/******/ } -/******/ if (!options.ignoreErrored) { -/******/ if (!error) error = err2; -/******/ } -/******/ if (!error) error = err; -/******/ } -/******/ } else { -/******/ if (options.onErrored) { -/******/ options.onErrored({ -/******/ type: "self-accept-errored", -/******/ moduleId: moduleId, -/******/ error: err -/******/ }); -/******/ } -/******/ if (!options.ignoreErrored) { -/******/ if (!error) error = err; -/******/ } -/******/ } -/******/ } -/******/ } -/******/ -/******/ // handle errors in accept handlers and self accepted module load -/******/ if (error) { -/******/ hotSetStatus("fail"); -/******/ return Promise.reject(error); -/******/ } -/******/ -/******/ if (hotQueuedInvalidatedModules) { -/******/ return hotApplyInternal(options).then(function(list) { -/******/ outdatedModules.forEach(function(moduleId) { -/******/ if (list.indexOf(moduleId) < 0) list.push(moduleId); -/******/ }); -/******/ return list; -/******/ }); -/******/ } -/******/ -/******/ hotSetStatus("idle"); -/******/ return new Promise(function(resolve) { -/******/ resolve(outdatedModules); -/******/ }); -/******/ } -/******/ -/******/ function hotApplyInvalidatedModules() { -/******/ if (hotQueuedInvalidatedModules) { -/******/ if (!hotUpdate) hotUpdate = {}; -/******/ hotQueuedInvalidatedModules.forEach(hotApplyInvalidatedModule); -/******/ hotQueuedInvalidatedModules = undefined; -/******/ return true; -/******/ } -/******/ } -/******/ -/******/ function hotApplyInvalidatedModule(moduleId) { -/******/ if (!Object.prototype.hasOwnProperty.call(hotUpdate, moduleId)) -/******/ hotUpdate[moduleId] = modules[moduleId]; -/******/ } -/******/ -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {}, -/******/ hot: hotCreateModule(moduleId), -/******/ parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp), -/******/ children: [] -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId)); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // __webpack_hash__ -/******/ __webpack_require__.h = function() { return hotCurrentHash; }; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return hotCreateRequire(0)(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin - - if(true) { - // - var cssReload = __webpack_require__(1)(module.i, {"locals":false}); - module.hot.dispose(cssReload); - module.hot.accept(undefined, cssReload); - } - - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint-env browser */ -/* - eslint-disable - no-console, - func-names -*/ - -const normalizeUrl = __webpack_require__(2); - -const srcByModuleId = Object.create(null); - -const noDocument = typeof document === 'undefined'; - -const { forEach } = Array.prototype; - -function debounce(fn, time) { - let timeout = 0; - - return function () { - const self = this; - // eslint-disable-next-line prefer-rest-params - const args = arguments; - - const functionCall = function functionCall() { - return fn.apply(self, args); - }; - - clearTimeout(timeout); - timeout = setTimeout(functionCall, time); - }; -} - -function noop() {} - -function getCurrentScriptUrl(moduleId) { - let src = srcByModuleId[moduleId]; - - if (!src) { - if (document.currentScript) { - ({ src } = document.currentScript); - } else { - const scripts = document.getElementsByTagName('script'); - const lastScriptTag = scripts[scripts.length - 1]; - - if (lastScriptTag) { - ({ src } = lastScriptTag); - } - } - - srcByModuleId[moduleId] = src; - } - - return function (fileMap) { - if (!src) { - return null; - } - - const splitResult = src.split(/([^\\/]+)\.js$/); - const filename = splitResult && splitResult[1]; - - if (!filename) { - return [src.replace('.js', '.css')]; - } - - if (!fileMap) { - return [src.replace('.js', '.css')]; - } - - return fileMap.split(',').map((mapRule) => { - const reg = new RegExp(`${filename}\\.js$`, 'g'); - - return normalizeUrl( - src.replace(reg, `${mapRule.replace(/{fileName}/g, filename)}.css`) - ); - }); - }; -} - -function updateCss(el, url) { - if (!url) { - if (!el.href) { - return; - } - - // eslint-disable-next-line - url = el.href.split('?')[0]; - } - - if (!isUrlRequest(url)) { - return; - } - - if (el.isLoaded === false) { - // We seem to be about to replace a css link that hasn't loaded yet. - // We're probably changing the same file more than once. - return; - } - - if (!url || !(url.indexOf('.css') > -1)) { - return; - } - - // eslint-disable-next-line no-param-reassign - el.visited = true; - - const newEl = el.cloneNode(); - - newEl.isLoaded = false; - - newEl.addEventListener('load', () => { - if (newEl.isLoaded) { - return; - } - - newEl.isLoaded = true; - el.parentNode.removeChild(el); - }); - - newEl.addEventListener('error', () => { - if (newEl.isLoaded) { - return; - } - - newEl.isLoaded = true; - el.parentNode.removeChild(el); - }); - - newEl.href = `${url}?${Date.now()}`; - - if (el.nextSibling) { - el.parentNode.insertBefore(newEl, el.nextSibling); - } else { - el.parentNode.appendChild(newEl); - } -} - -function getReloadUrl(href, src) { - let ret; - - // eslint-disable-next-line no-param-reassign - href = normalizeUrl(href, { stripWWW: false }); - - // eslint-disable-next-line array-callback-return - src.some((url) => { - if (href.indexOf(src) > -1) { - ret = url; - } - }); - - return ret; -} - -function reloadStyle(src) { - if (!src) { - return false; - } - - const elements = document.querySelectorAll('link'); - let loaded = false; - - forEach.call(elements, (el) => { - if (!el.href) { - return; - } - - const url = getReloadUrl(el.href, src); - - if (!isUrlRequest(url)) { - return; - } - - if (el.visited === true) { - return; - } - - if (url) { - updateCss(el, url); - - loaded = true; - } - }); - - return loaded; -} - -function reloadAll() { - const elements = document.querySelectorAll('link'); - - forEach.call(elements, (el) => { - if (el.visited === true) { - return; - } - - updateCss(el); - }); -} - -function isUrlRequest(url) { - // An URL is not an request if - - // It is not http or https - if (!/^https?:/i.test(url)) { - return false; - } - - return true; -} - -module.exports = function (moduleId, options) { - if (noDocument) { - console.log('no window.document found, will not HMR CSS'); - - return noop; - } - - const getScriptSrc = getCurrentScriptUrl(moduleId); - - function update() { - const src = getScriptSrc(options.filename); - const reloaded = reloadStyle(src); - - if (options.locals) { - console.log('[HMR] Detected local css modules. Reload all css'); - - reloadAll(); - - return; - } - - if (reloaded) { - console.log('[HMR] css reload %s', src.join(' ')); - } else { - console.log('[HMR] Reload all css'); - - reloadAll(); - } - } - - return debounce(update, 50); -}; - - -/***/ }), -/* 2 */ -/***/ (function(module, exports) { - -/* eslint-disable */ - -function normalizeUrl(pathComponents) { - return pathComponents - .reduce(function (accumulator, item) { - switch (item) { - case '..': - accumulator.pop(); - break; - case '.': - break; - default: - accumulator.push(item); - } - - return accumulator; - }, []) - .join('/'); -} - -module.exports = function (urlString) { - urlString = urlString.trim(); - - if (/^data:/i.test(urlString)) { - return urlString; - } - - var protocol = - urlString.indexOf('//') !== -1 ? urlString.split('//')[0] + '//' : ''; - var components = urlString.replace(new RegExp(protocol, 'i'), '').split('/'); - var host = components[0].toLowerCase().replace(/\.$/, ''); - - components[0] = ''; - - var path = normalizeUrl(components); - - return protocol + host + path; -}; - - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/test/cases/insert-function/expected/webpack-4/1.css b/test/cases/insert-function/expected/webpack-4/1.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/insert-function/expected/webpack-4/1.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/insert-function/expected/webpack-4/1.js b/test/cases/insert-function/expected/webpack-4/1.js deleted file mode 100644 index 4292040c..00000000 --- a/test/cases/insert-function/expected/webpack-4/1.js +++ /dev/null @@ -1,12 +0,0 @@ -(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ -/* 0 */, -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin - - -/***/ }) -]]); \ No newline at end of file diff --git a/test/cases/insert-function/expected/webpack-4/main.js b/test/cases/insert-function/expected/webpack-4/main.js deleted file mode 100644 index 469a9aa6..00000000 --- a/test/cases/insert-function/expected/webpack-4/main.js +++ /dev/null @@ -1,273 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // install a JSONP callback for chunk loading -/******/ function webpackJsonpCallback(data) { -/******/ var chunkIds = data[0]; -/******/ var moreModules = data[1]; -/******/ -/******/ -/******/ // add "moreModules" to the modules object, -/******/ // then flag all "chunkIds" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0, resolves = []; -/******/ for(;i < chunkIds.length; i++) { -/******/ chunkId = chunkIds[i]; -/******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ resolves.push(installedChunks[chunkId][0]); -/******/ } -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { -/******/ modules[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(parentJsonpFunction) parentJsonpFunction(data); -/******/ -/******/ while(resolves.length) { -/******/ resolves.shift()(); -/******/ } -/******/ -/******/ }; -/******/ -/******/ -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // object to store loaded CSS chunks -/******/ var installedCssChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // Promise = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ -/******/ -/******/ // script path function -/******/ function jsonpScriptSrc(chunkId) { -/******/ return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js" -/******/ } -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // This file contains only the entry chunk. -/******/ // The chunk loading function for additional chunks -/******/ __webpack_require__.e = function requireEnsure(chunkId) { -/******/ var promises = []; -/******/ -/******/ -/******/ // mini-css-extract-plugin CSS loading -/******/ var cssChunks = {"1":1}; -/******/ if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]); -/******/ else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) { -/******/ promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) { -/******/ var href = "" + chunkId + ".css"; -/******/ var fullhref = __webpack_require__.p + href; -/******/ var existingLinkTags = document.getElementsByTagName("link"); -/******/ for(var i = 0; i < existingLinkTags.length; i++) { -/******/ 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++) { -/******/ 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"; -/******/ var onLinkComplete = function (event) { -/******/ // avoid mem leaks. -/******/ linkTag.onerror = linkTag.onload = null; -/******/ if (event.type === 'load') { -/******/ resolve(); -/******/ } else { -/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); -/******/ var realHref = event && event.target && event.target.href || fullhref; -/******/ var err = new Error("Loading CSS chunk " + chunkId + " failed.\n(" + realHref + ")"); -/******/ err.code = "CSS_CHUNK_LOAD_FAILED"; -/******/ err.type = errorType; -/******/ err.request = realHref; -/******/ delete installedCssChunks[chunkId] -/******/ linkTag.parentNode.removeChild(linkTag) -/******/ reject(err); -/******/ } -/******/ }; -/******/ linkTag.onerror = linkTag.onload = onLinkComplete; -/******/ linkTag.href = fullhref; -/******/ -/******/ (function (linkTag) { -/******/ const reference = document.querySelector('.hot-reload'); -/******/ -/******/ if (reference) { -/******/ reference.parentNode.insertBefore(linkTag, reference); -/******/ } -/******/ })(linkTag) -/******/ }).then(function() { -/******/ installedCssChunks[chunkId] = 0; -/******/ })); -/******/ } -/******/ -/******/ // JSONP chunk loading for javascript -/******/ -/******/ var installedChunkData = installedChunks[chunkId]; -/******/ if(installedChunkData !== 0) { // 0 means "already installed". -/******/ -/******/ // a Promise means "currently loading". -/******/ if(installedChunkData) { -/******/ promises.push(installedChunkData[2]); -/******/ } else { -/******/ // setup Promise in chunk cache -/******/ var promise = new Promise(function(resolve, reject) { -/******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; -/******/ }); -/******/ promises.push(installedChunkData[2] = promise); -/******/ -/******/ // start chunk loading -/******/ var script = document.createElement('script'); -/******/ var onScriptComplete; -/******/ -/******/ script.charset = 'utf-8'; -/******/ script.timeout = 120; -/******/ if (__webpack_require__.nc) { -/******/ script.setAttribute("nonce", __webpack_require__.nc); -/******/ } -/******/ script.src = jsonpScriptSrc(chunkId); -/******/ -/******/ // create error before stack unwound to get useful stacktrace later -/******/ var error = new Error(); -/******/ onScriptComplete = function (event) { -/******/ // avoid mem leaks in IE. -/******/ script.onerror = script.onload = null; -/******/ clearTimeout(timeout); -/******/ var chunk = installedChunks[chunkId]; -/******/ if(chunk !== 0) { -/******/ if(chunk) { -/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); -/******/ var realSrc = event && event.target && event.target.src; -/******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'; -/******/ error.name = 'ChunkLoadError'; -/******/ error.type = errorType; -/******/ error.request = realSrc; -/******/ chunk[1](error); -/******/ } -/******/ installedChunks[chunkId] = undefined; -/******/ } -/******/ }; -/******/ var timeout = setTimeout(function(){ -/******/ onScriptComplete({ type: 'timeout', target: script }); -/******/ }, 120000); -/******/ script.onerror = script.onload = onScriptComplete; -/******/ document.head.appendChild(script); -/******/ } -/******/ } -/******/ return Promise.all(promises); -/******/ }; -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // on error function for async loading -/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; -/******/ -/******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; -/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); -/******/ jsonpArray.push = webpackJsonpCallback; -/******/ jsonpArray = jsonpArray.slice(); -/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); -/******/ var parentJsonpFunction = oldJsonpFunction; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint-env browser */ - -// eslint-disable-next-line -__webpack_require__.e(/* import() */ 1).then(__webpack_require__.bind(null, 1)); - - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/test/cases/insert-string/expected/webpack-4/1.css b/test/cases/insert-string/expected/webpack-4/1.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/insert-string/expected/webpack-4/1.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/insert-string/expected/webpack-4/1.js b/test/cases/insert-string/expected/webpack-4/1.js deleted file mode 100644 index 4292040c..00000000 --- a/test/cases/insert-string/expected/webpack-4/1.js +++ /dev/null @@ -1,12 +0,0 @@ -(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ -/* 0 */, -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin - - -/***/ }) -]]); \ No newline at end of file diff --git a/test/cases/insert-string/expected/webpack-4/main.js b/test/cases/insert-string/expected/webpack-4/main.js deleted file mode 100644 index 9af8b299..00000000 --- a/test/cases/insert-string/expected/webpack-4/main.js +++ /dev/null @@ -1,268 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // install a JSONP callback for chunk loading -/******/ function webpackJsonpCallback(data) { -/******/ var chunkIds = data[0]; -/******/ var moreModules = data[1]; -/******/ -/******/ -/******/ // add "moreModules" to the modules object, -/******/ // then flag all "chunkIds" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0, resolves = []; -/******/ for(;i < chunkIds.length; i++) { -/******/ chunkId = chunkIds[i]; -/******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ resolves.push(installedChunks[chunkId][0]); -/******/ } -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { -/******/ modules[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(parentJsonpFunction) parentJsonpFunction(data); -/******/ -/******/ while(resolves.length) { -/******/ resolves.shift()(); -/******/ } -/******/ -/******/ }; -/******/ -/******/ -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // object to store loaded CSS chunks -/******/ var installedCssChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // Promise = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ -/******/ -/******/ // script path function -/******/ function jsonpScriptSrc(chunkId) { -/******/ return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js" -/******/ } -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // This file contains only the entry chunk. -/******/ // The chunk loading function for additional chunks -/******/ __webpack_require__.e = function requireEnsure(chunkId) { -/******/ var promises = []; -/******/ -/******/ -/******/ // mini-css-extract-plugin CSS loading -/******/ var cssChunks = {"1":1}; -/******/ if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]); -/******/ else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) { -/******/ promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) { -/******/ var href = "" + chunkId + ".css"; -/******/ var fullhref = __webpack_require__.p + href; -/******/ var existingLinkTags = document.getElementsByTagName("link"); -/******/ for(var i = 0; i < existingLinkTags.length; i++) { -/******/ 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++) { -/******/ 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"; -/******/ var onLinkComplete = function (event) { -/******/ // avoid mem leaks. -/******/ linkTag.onerror = linkTag.onload = null; -/******/ if (event.type === 'load') { -/******/ resolve(); -/******/ } else { -/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); -/******/ var realHref = event && event.target && event.target.href || fullhref; -/******/ var err = new Error("Loading CSS chunk " + chunkId + " failed.\n(" + realHref + ")"); -/******/ err.code = "CSS_CHUNK_LOAD_FAILED"; -/******/ err.type = errorType; -/******/ err.request = realHref; -/******/ delete installedCssChunks[chunkId] -/******/ linkTag.parentNode.removeChild(linkTag) -/******/ reject(err); -/******/ } -/******/ }; -/******/ linkTag.onerror = linkTag.onload = onLinkComplete; -/******/ linkTag.href = fullhref; -/******/ -/******/ var target = document.querySelector("script[src='1.js']"); -/******/ target.parentNode.insertBefore(linkTag, target.nextSibling); -/******/ }).then(function() { -/******/ installedCssChunks[chunkId] = 0; -/******/ })); -/******/ } -/******/ -/******/ // JSONP chunk loading for javascript -/******/ -/******/ var installedChunkData = installedChunks[chunkId]; -/******/ if(installedChunkData !== 0) { // 0 means "already installed". -/******/ -/******/ // a Promise means "currently loading". -/******/ if(installedChunkData) { -/******/ promises.push(installedChunkData[2]); -/******/ } else { -/******/ // setup Promise in chunk cache -/******/ var promise = new Promise(function(resolve, reject) { -/******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; -/******/ }); -/******/ promises.push(installedChunkData[2] = promise); -/******/ -/******/ // start chunk loading -/******/ var script = document.createElement('script'); -/******/ var onScriptComplete; -/******/ -/******/ script.charset = 'utf-8'; -/******/ script.timeout = 120; -/******/ if (__webpack_require__.nc) { -/******/ script.setAttribute("nonce", __webpack_require__.nc); -/******/ } -/******/ script.src = jsonpScriptSrc(chunkId); -/******/ -/******/ // create error before stack unwound to get useful stacktrace later -/******/ var error = new Error(); -/******/ onScriptComplete = function (event) { -/******/ // avoid mem leaks in IE. -/******/ script.onerror = script.onload = null; -/******/ clearTimeout(timeout); -/******/ var chunk = installedChunks[chunkId]; -/******/ if(chunk !== 0) { -/******/ if(chunk) { -/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); -/******/ var realSrc = event && event.target && event.target.src; -/******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'; -/******/ error.name = 'ChunkLoadError'; -/******/ error.type = errorType; -/******/ error.request = realSrc; -/******/ chunk[1](error); -/******/ } -/******/ installedChunks[chunkId] = undefined; -/******/ } -/******/ }; -/******/ var timeout = setTimeout(function(){ -/******/ onScriptComplete({ type: 'timeout', target: script }); -/******/ }, 120000); -/******/ script.onerror = script.onload = onScriptComplete; -/******/ document.head.appendChild(script); -/******/ } -/******/ } -/******/ return Promise.all(promises); -/******/ }; -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // on error function for async loading -/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; -/******/ -/******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; -/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); -/******/ jsonpArray.push = webpackJsonpCallback; -/******/ jsonpArray = jsonpArray.slice(); -/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); -/******/ var parentJsonpFunction = oldJsonpFunction; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint-env browser */ - -// eslint-disable-next-line -__webpack_require__.e(/* import() */ 1).then(__webpack_require__.bind(null, 1)); - - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/test/cases/insert-undefined/expected/webpack-4/1.css b/test/cases/insert-undefined/expected/webpack-4/1.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/insert-undefined/expected/webpack-4/1.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/insert-undefined/expected/webpack-4/1.js b/test/cases/insert-undefined/expected/webpack-4/1.js deleted file mode 100644 index 4292040c..00000000 --- a/test/cases/insert-undefined/expected/webpack-4/1.js +++ /dev/null @@ -1,12 +0,0 @@ -(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[ -/* 0 */, -/* 1 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin - - -/***/ }) -]]); \ No newline at end of file diff --git a/test/cases/insert-undefined/expected/webpack-4/main.js b/test/cases/insert-undefined/expected/webpack-4/main.js deleted file mode 100644 index dffcd674..00000000 --- a/test/cases/insert-undefined/expected/webpack-4/main.js +++ /dev/null @@ -1,267 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // install a JSONP callback for chunk loading -/******/ function webpackJsonpCallback(data) { -/******/ var chunkIds = data[0]; -/******/ var moreModules = data[1]; -/******/ -/******/ -/******/ // add "moreModules" to the modules object, -/******/ // then flag all "chunkIds" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0, resolves = []; -/******/ for(;i < chunkIds.length; i++) { -/******/ chunkId = chunkIds[i]; -/******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ resolves.push(installedChunks[chunkId][0]); -/******/ } -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { -/******/ modules[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(parentJsonpFunction) parentJsonpFunction(data); -/******/ -/******/ while(resolves.length) { -/******/ resolves.shift()(); -/******/ } -/******/ -/******/ }; -/******/ -/******/ -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // object to store loaded CSS chunks -/******/ var installedCssChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // Promise = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ -/******/ -/******/ // script path function -/******/ function jsonpScriptSrc(chunkId) { -/******/ return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js" -/******/ } -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // This file contains only the entry chunk. -/******/ // The chunk loading function for additional chunks -/******/ __webpack_require__.e = function requireEnsure(chunkId) { -/******/ var promises = []; -/******/ -/******/ -/******/ // mini-css-extract-plugin CSS loading -/******/ var cssChunks = {"1":1}; -/******/ if(installedCssChunks[chunkId]) promises.push(installedCssChunks[chunkId]); -/******/ else if(installedCssChunks[chunkId] !== 0 && cssChunks[chunkId]) { -/******/ promises.push(installedCssChunks[chunkId] = new Promise(function(resolve, reject) { -/******/ var href = "" + chunkId + ".css"; -/******/ var fullhref = __webpack_require__.p + href; -/******/ var existingLinkTags = document.getElementsByTagName("link"); -/******/ for(var i = 0; i < existingLinkTags.length; i++) { -/******/ 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++) { -/******/ 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"; -/******/ var onLinkComplete = function (event) { -/******/ // avoid mem leaks. -/******/ linkTag.onerror = linkTag.onload = null; -/******/ if (event.type === 'load') { -/******/ resolve(); -/******/ } else { -/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); -/******/ var realHref = event && event.target && event.target.href || fullhref; -/******/ var err = new Error("Loading CSS chunk " + chunkId + " failed.\n(" + realHref + ")"); -/******/ err.code = "CSS_CHUNK_LOAD_FAILED"; -/******/ err.type = errorType; -/******/ err.request = realHref; -/******/ delete installedCssChunks[chunkId] -/******/ linkTag.parentNode.removeChild(linkTag) -/******/ reject(err); -/******/ } -/******/ }; -/******/ linkTag.onerror = linkTag.onload = onLinkComplete; -/******/ linkTag.href = fullhref; -/******/ -/******/ document.head.appendChild(linkTag); -/******/ }).then(function() { -/******/ installedCssChunks[chunkId] = 0; -/******/ })); -/******/ } -/******/ -/******/ // JSONP chunk loading for javascript -/******/ -/******/ var installedChunkData = installedChunks[chunkId]; -/******/ if(installedChunkData !== 0) { // 0 means "already installed". -/******/ -/******/ // a Promise means "currently loading". -/******/ if(installedChunkData) { -/******/ promises.push(installedChunkData[2]); -/******/ } else { -/******/ // setup Promise in chunk cache -/******/ var promise = new Promise(function(resolve, reject) { -/******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; -/******/ }); -/******/ promises.push(installedChunkData[2] = promise); -/******/ -/******/ // start chunk loading -/******/ var script = document.createElement('script'); -/******/ var onScriptComplete; -/******/ -/******/ script.charset = 'utf-8'; -/******/ script.timeout = 120; -/******/ if (__webpack_require__.nc) { -/******/ script.setAttribute("nonce", __webpack_require__.nc); -/******/ } -/******/ script.src = jsonpScriptSrc(chunkId); -/******/ -/******/ // create error before stack unwound to get useful stacktrace later -/******/ var error = new Error(); -/******/ onScriptComplete = function (event) { -/******/ // avoid mem leaks in IE. -/******/ script.onerror = script.onload = null; -/******/ clearTimeout(timeout); -/******/ var chunk = installedChunks[chunkId]; -/******/ if(chunk !== 0) { -/******/ if(chunk) { -/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); -/******/ var realSrc = event && event.target && event.target.src; -/******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'; -/******/ error.name = 'ChunkLoadError'; -/******/ error.type = errorType; -/******/ error.request = realSrc; -/******/ chunk[1](error); -/******/ } -/******/ installedChunks[chunkId] = undefined; -/******/ } -/******/ }; -/******/ var timeout = setTimeout(function(){ -/******/ onScriptComplete({ type: 'timeout', target: script }); -/******/ }, 120000); -/******/ script.onerror = script.onload = onScriptComplete; -/******/ document.head.appendChild(script); -/******/ } -/******/ } -/******/ return Promise.all(promises); -/******/ }; -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // on error function for async loading -/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; -/******/ -/******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; -/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); -/******/ jsonpArray.push = webpackJsonpCallback; -/******/ jsonpArray = jsonpArray.slice(); -/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); -/******/ var parentJsonpFunction = oldJsonpFunction; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 0); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, exports, __webpack_require__) { - -/* eslint-env browser */ - -// eslint-disable-next-line -__webpack_require__.e(/* import() */ 1).then(__webpack_require__.bind(null, 1)); - - -/***/ }) -/******/ ]); \ No newline at end of file diff --git a/test/cases/js-hash/expected/webpack-4/style.30d1e86f422f446d669b.1.css b/test/cases/js-hash/expected/webpack-4/style.30d1e86f422f446d669b.1.css deleted file mode 100644 index c7349e60..00000000 --- a/test/cases/js-hash/expected/webpack-4/style.30d1e86f422f446d669b.1.css +++ /dev/null @@ -1,4 +0,0 @@ -._1vsR78e9UKJf5jCq7eLSYu { - background: red; -} - diff --git a/test/cases/js-hash/expected/webpack-4/style.b80413d497a74d66cee9.2.css b/test/cases/js-hash/expected/webpack-4/style.b80413d497a74d66cee9.2.css deleted file mode 100644 index 0f225f15..00000000 --- a/test/cases/js-hash/expected/webpack-4/style.b80413d497a74d66cee9.2.css +++ /dev/null @@ -1,5 +0,0 @@ - -._1vsR78e9UKJf5jCq7eLSYu { - background: green; -} - diff --git a/test/cases/new-url-with-public-path-auto/test.filter.js b/test/cases/new-url-with-public-path-auto/test.filter.js index 20341d78..d04b7de0 100644 --- a/test/cases/new-url-with-public-path-auto/test.filter.js +++ b/test/cases/new-url-with-public-path-auto/test.filter.js @@ -1,4 +1 @@ -const webpack = require('webpack'); - -module.exports = () => - webpack.version[0] !== '4' && !process.env.EXPERIMENTAL_USE_IMPORT_MODULE; +module.exports = () => !process.env.EXPERIMENTAL_USE_IMPORT_MODULE; diff --git a/test/cases/new-url-with-public-path/test.filter.js b/test/cases/new-url-with-public-path/test.filter.js index 20341d78..d04b7de0 100644 --- a/test/cases/new-url-with-public-path/test.filter.js +++ b/test/cases/new-url-with-public-path/test.filter.js @@ -1,4 +1 @@ -const webpack = require('webpack'); - -module.exports = () => - webpack.version[0] !== '4' && !process.env.EXPERIMENTAL_USE_IMPORT_MODULE; +module.exports = () => !process.env.EXPERIMENTAL_USE_IMPORT_MODULE; diff --git a/test/cases/new-url-with-public-path/webpack.config.js b/test/cases/new-url-with-public-path/webpack.config.js index 1d7453d9..0b819e77 100644 --- a/test/cases/new-url-with-public-path/webpack.config.js +++ b/test/cases/new-url-with-public-path/webpack.config.js @@ -13,7 +13,7 @@ module.exports = { { loader: Self.loader, options: { - publicPath: 'public', + publicPath: 'public/', }, }, './mockLoader', diff --git a/test/cases/publicpath-auto-2/expected/assets/img/react.svg b/test/cases/publicpath-auto-2/expected/assets/img/react.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/expected/assets/img/react.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/expected/same_root.svg b/test/cases/publicpath-auto-2/expected/same_root.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/expected/same_root.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/expected/styles/main.css b/test/cases/publicpath-auto-2/expected/styles/main.css new file mode 100644 index 00000000..ce980054 --- /dev/null +++ b/test/cases/publicpath-auto-2/expected/styles/main.css @@ -0,0 +1,20 @@ +.a { + background-image: url(../same_root.svg); +} + +.b { + background-image: url(../styles/same_dir.svg); +} + +.c { + background-image: url(../styles/nested/nested_dir.svg); +} + +.d { + background-image: url(../../outer.svg); +} + +.e { + background-image: url(../assets/img/react.svg); +} + diff --git a/test/cases/publicpath-auto-2/expected/styles/nested/nested_dir.svg b/test/cases/publicpath-auto-2/expected/styles/nested/nested_dir.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/expected/styles/nested/nested_dir.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/expected/styles/same_dir.svg b/test/cases/publicpath-auto-2/expected/styles/same_dir.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/expected/styles/same_dir.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/images/react.svg b/test/cases/publicpath-auto-2/images/react.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/images/react.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/index.js b/test/cases/publicpath-auto-2/index.js new file mode 100644 index 00000000..aa3357bf --- /dev/null +++ b/test/cases/publicpath-auto-2/index.js @@ -0,0 +1 @@ +import './style.css'; diff --git a/test/cases/publicpath-auto-2/nested_dir.svg b/test/cases/publicpath-auto-2/nested_dir.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/nested_dir.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/outer.svg b/test/cases/publicpath-auto-2/outer.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/outer.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/same_dir.svg b/test/cases/publicpath-auto-2/same_dir.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/same_dir.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/same_root.svg b/test/cases/publicpath-auto-2/same_root.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-2/same_root.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-2/style.css b/test/cases/publicpath-auto-2/style.css new file mode 100644 index 00000000..aacb0169 --- /dev/null +++ b/test/cases/publicpath-auto-2/style.css @@ -0,0 +1,19 @@ +.a { + background-image: url(./same_root.svg); +} + +.b { + background-image: url(./same_dir.svg); +} + +.c { + background-image: url(./nested_dir.svg); +} + +.d { + background-image: url(./outer.svg); +} + +.e { + background-image: url(./images/react.svg); +} diff --git a/test/cases/publicpath-auto-2/webpack.config.js b/test/cases/publicpath-auto-2/webpack.config.js new file mode 100644 index 00000000..5f11917b --- /dev/null +++ b/test/cases/publicpath-auto-2/webpack.config.js @@ -0,0 +1,51 @@ +import Self from '../../../src'; + +module.exports = { + entry: './index.js', + output: { + publicPath: 'auto', + }, + module: { + rules: [ + { + test: /\.css$/, + use: [ + { + loader: Self.loader, + }, + 'css-loader', + ], + }, + { + test: /outer\.(svg)$/, + type: 'asset/resource', + generator: { filename: '../[name][ext]' }, + }, + { + test: /same_root\.(svg)$/, + type: 'asset/resource', + generator: { filename: '[name][ext]' }, + }, + { + test: /same_dir\.(svg)$/, + type: 'asset/resource', + generator: { filename: 'styles/[name][ext]' }, + }, + { + test: /nested_dir\.(svg)$/, + type: 'asset/resource', + generator: { filename: 'styles/nested/[name][ext]' }, + }, + { + test: /react\.(svg)$/, + type: 'asset/resource', + generator: { filename: 'assets/img/[name][ext]' }, + }, + ], + }, + plugins: [ + new Self({ + filename: 'styles/[name].css', + }), + ], +}; diff --git a/test/cases/publicpath-auto-3/expected/assets/img/react.svg b/test/cases/publicpath-auto-3/expected/assets/img/react.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/expected/assets/img/react.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/expected/assets/img2.svg b/test/cases/publicpath-auto-3/expected/assets/img2.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/expected/assets/img2.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/expected/assets/nested/img3.svg b/test/cases/publicpath-auto-3/expected/assets/nested/img3.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/expected/assets/nested/img3.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/expected/img1.svg b/test/cases/publicpath-auto-3/expected/img1.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/expected/img1.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/expected/img4.svg b/test/cases/publicpath-auto-3/expected/img4.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/expected/img4.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/expected/main.css b/test/cases/publicpath-auto-3/expected/main.css new file mode 100644 index 00000000..a0162fed --- /dev/null +++ b/test/cases/publicpath-auto-3/expected/main.css @@ -0,0 +1,24 @@ +.a { + background-image: url(img1.svg); +} + +.b { + background-image: url(assets/img2.svg); +} + +.c { + background-image: url(assets/nested/img3.svg); +} + +.d { + background-image: url(img4.svg); +} + +.e { + background-image: url(assets/img/react.svg); +} + +.f { + background-image: url(../outer.svg); +} + diff --git a/test/cases/publicpath-auto-3/images/react.svg b/test/cases/publicpath-auto-3/images/react.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/images/react.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/img2.svg b/test/cases/publicpath-auto-3/img2.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/img2.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/img3.svg b/test/cases/publicpath-auto-3/img3.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/img3.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/index.js b/test/cases/publicpath-auto-3/index.js new file mode 100644 index 00000000..cfc06994 --- /dev/null +++ b/test/cases/publicpath-auto-3/index.js @@ -0,0 +1 @@ +import './src/styles/style.css'; diff --git a/test/cases/publicpath-auto-3/outer.svg b/test/cases/publicpath-auto-3/outer.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/outer.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/src/styles/img/img4.svg b/test/cases/publicpath-auto-3/src/styles/img/img4.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/src/styles/img/img4.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/src/styles/img1.svg b/test/cases/publicpath-auto-3/src/styles/img1.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto-3/src/styles/img1.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto-3/src/styles/style.css b/test/cases/publicpath-auto-3/src/styles/style.css new file mode 100644 index 00000000..783b19f7 --- /dev/null +++ b/test/cases/publicpath-auto-3/src/styles/style.css @@ -0,0 +1,23 @@ +.a { + background-image: url(img1.svg); +} + +.b { + background-image: url(../../img2.svg); +} + +.c { + background-image: url(../../img3.svg); +} + +.d { + background-image: url(img/img4.svg); +} + +.e { + background-image: url(../../images/react.svg); +} + +.f { + background-image: url(../../outer.svg); +} diff --git a/test/cases/publicpath-auto-3/webpack.config.js b/test/cases/publicpath-auto-3/webpack.config.js new file mode 100644 index 00000000..1926f6ef --- /dev/null +++ b/test/cases/publicpath-auto-3/webpack.config.js @@ -0,0 +1,56 @@ +import Self from '../../../src'; + +module.exports = { + entry: './index.js', + module: { + rules: [ + { + test: /\.css$/, + use: [ + { + loader: Self.loader, + options: { + publicPath: 'auto', + }, + }, + 'css-loader', + ], + }, + { + test: /outer\.(svg)$/, + type: 'asset/resource', + generator: { filename: '../[name][ext]' }, + }, + { + test: /img1\.(svg)$/, + type: 'asset/resource', + generator: { filename: '[name][ext]' }, + }, + { + test: /img2\.(svg)$/, + type: 'asset/resource', + generator: { filename: 'assets/[name][ext]' }, + }, + { + test: /img3\.(svg)$/, + type: 'asset/resource', + generator: { filename: 'assets/nested/[name][ext]' }, + }, + { + test: /img4\.(svg)$/, + type: 'asset/resource', + generator: { filename: '[name][ext]' }, + }, + { + test: /react\.(svg)$/, + type: 'asset/resource', + generator: { filename: 'assets/img/[name][ext]' }, + }, + ], + }, + plugins: [ + new Self({ + filename: '[name].css', + }), + ], +}; diff --git a/test/cases/publicpath-auto/expected/assets/react.svg b/test/cases/publicpath-auto/expected/assets/react.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto/expected/assets/react.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto/expected/styles/a25f373965b6e21a1ef0/main.css b/test/cases/publicpath-auto/expected/styles/a25f373965b6e21a1ef0/main.css new file mode 100644 index 00000000..6b63f890 --- /dev/null +++ b/test/cases/publicpath-auto/expected/styles/a25f373965b6e21a1ef0/main.css @@ -0,0 +1,5 @@ +body { + background: red; + background-image: url(../../assets/react.svg); +} + diff --git a/test/cases/publicpath-auto/index.js b/test/cases/publicpath-auto/index.js new file mode 100644 index 00000000..aa3357bf --- /dev/null +++ b/test/cases/publicpath-auto/index.js @@ -0,0 +1 @@ +import './style.css'; diff --git a/test/cases/publicpath-auto/react.svg b/test/cases/publicpath-auto/react.svg new file mode 100644 index 00000000..5b3b22a4 --- /dev/null +++ b/test/cases/publicpath-auto/react.svg @@ -0,0 +1 @@ +logo-on-dark-bg \ No newline at end of file diff --git a/test/cases/publicpath-auto/style.css b/test/cases/publicpath-auto/style.css new file mode 100644 index 00000000..52c2b3e4 --- /dev/null +++ b/test/cases/publicpath-auto/style.css @@ -0,0 +1,4 @@ +body { + background: red; + background-image: url(./react.svg); +} diff --git a/test/cases/publicpath-auto/webpack.config.js b/test/cases/publicpath-auto/webpack.config.js new file mode 100644 index 00000000..e1d69512 --- /dev/null +++ b/test/cases/publicpath-auto/webpack.config.js @@ -0,0 +1,31 @@ +import Self from '../../../src'; + +module.exports = { + entry: './index.js', + module: { + rules: [ + { + test: /\.css$/, + use: [ + { + loader: Self.loader, + options: { + publicPath: 'auto', + }, + }, + 'css-loader', + ], + }, + { + test: /\.(svg|png)$/, + type: 'asset/resource', + generator: { filename: 'assets/[name][ext]' }, + }, + ], + }, + plugins: [ + new Self({ + filename: 'styles/[contenthash]/[name].css', + }), + ], +}; diff --git a/test/cases/publicpath-trailing-slash/expected/main.css b/test/cases/publicpath-trailing-slash/expected/main.css deleted file mode 100644 index 6d14c42a..00000000 --- a/test/cases/publicpath-trailing-slash/expected/main.css +++ /dev/null @@ -1,5 +0,0 @@ -body { - background: red; - background-image: url(/static/img/c9e192c015437a21dea1faa1d30f4941.svg); -} - diff --git a/test/cases/runtime/expected/webpack-4/main.c4d90d38e7a606ae4d4c.css b/test/cases/runtime/expected/webpack-4/main.c4d90d38e7a606ae4d4c.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/runtime/expected/webpack-4/main.c4d90d38e7a606ae4d4c.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/runtime/expected/webpack-4/runtime~main.js b/test/cases/runtime/expected/webpack-4/runtime~main.js deleted file mode 100644 index 27b6ee56..00000000 --- a/test/cases/runtime/expected/webpack-4/runtime~main.js +++ /dev/null @@ -1,223 +0,0 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // install a JSONP callback for chunk loading -/******/ function webpackJsonpCallback(data) { -/******/ var chunkIds = data[0]; -/******/ var moreModules = data[1]; -/******/ var executeModules = data[2]; -/******/ -/******/ // add "moreModules" to the modules object, -/******/ // then flag all "chunkIds" as loaded and fire callback -/******/ var moduleId, chunkId, i = 0, resolves = []; -/******/ for(;i < chunkIds.length; i++) { -/******/ chunkId = chunkIds[i]; -/******/ if(Object.prototype.hasOwnProperty.call(installedChunks, chunkId) && installedChunks[chunkId]) { -/******/ resolves.push(installedChunks[chunkId][0]); -/******/ } -/******/ installedChunks[chunkId] = 0; -/******/ } -/******/ for(moduleId in moreModules) { -/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { -/******/ modules[moduleId] = moreModules[moduleId]; -/******/ } -/******/ } -/******/ if(parentJsonpFunction) parentJsonpFunction(data); -/******/ -/******/ while(resolves.length) { -/******/ resolves.shift()(); -/******/ } -/******/ -/******/ // add entry modules from loaded chunk to deferred list -/******/ deferredModules.push.apply(deferredModules, executeModules || []); -/******/ -/******/ // run deferred modules when all chunks ready -/******/ return checkDeferredModules(); -/******/ }; -/******/ function checkDeferredModules() { -/******/ var result; -/******/ for(var i = 0; i < deferredModules.length; i++) { -/******/ var deferredModule = deferredModules[i]; -/******/ var fulfilled = true; -/******/ for(var j = 1; j < deferredModule.length; j++) { -/******/ var depId = deferredModule[j]; -/******/ if(installedChunks[depId] !== 0) fulfilled = false; -/******/ } -/******/ if(fulfilled) { -/******/ deferredModules.splice(i--, 1); -/******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); -/******/ } -/******/ } -/******/ -/******/ return result; -/******/ } -/******/ -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // object to store loaded and loading chunks -/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched -/******/ // Promise = chunk loading, 0 = chunk loaded -/******/ var installedChunks = { -/******/ 0: 0 -/******/ }; -/******/ -/******/ var deferredModules = []; -/******/ -/******/ // script path function -/******/ function jsonpScriptSrc(chunkId) { -/******/ return __webpack_require__.p + "" + ({}[chunkId]||chunkId) + ".js" -/******/ } -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ // This file contains only the entry chunk. -/******/ // The chunk loading function for additional chunks -/******/ __webpack_require__.e = function requireEnsure(chunkId) { -/******/ var promises = []; -/******/ -/******/ -/******/ // JSONP chunk loading for javascript -/******/ -/******/ var installedChunkData = installedChunks[chunkId]; -/******/ if(installedChunkData !== 0) { // 0 means "already installed". -/******/ -/******/ // a Promise means "currently loading". -/******/ if(installedChunkData) { -/******/ promises.push(installedChunkData[2]); -/******/ } else { -/******/ // setup Promise in chunk cache -/******/ var promise = new Promise(function(resolve, reject) { -/******/ installedChunkData = installedChunks[chunkId] = [resolve, reject]; -/******/ }); -/******/ promises.push(installedChunkData[2] = promise); -/******/ -/******/ // start chunk loading -/******/ var script = document.createElement('script'); -/******/ var onScriptComplete; -/******/ -/******/ script.charset = 'utf-8'; -/******/ script.timeout = 120; -/******/ if (__webpack_require__.nc) { -/******/ script.setAttribute("nonce", __webpack_require__.nc); -/******/ } -/******/ script.src = jsonpScriptSrc(chunkId); -/******/ -/******/ // create error before stack unwound to get useful stacktrace later -/******/ var error = new Error(); -/******/ onScriptComplete = function (event) { -/******/ // avoid mem leaks in IE. -/******/ script.onerror = script.onload = null; -/******/ clearTimeout(timeout); -/******/ var chunk = installedChunks[chunkId]; -/******/ if(chunk !== 0) { -/******/ if(chunk) { -/******/ var errorType = event && (event.type === 'load' ? 'missing' : event.type); -/******/ var realSrc = event && event.target && event.target.src; -/******/ error.message = 'Loading chunk ' + chunkId + ' failed.\n(' + errorType + ': ' + realSrc + ')'; -/******/ error.name = 'ChunkLoadError'; -/******/ error.type = errorType; -/******/ error.request = realSrc; -/******/ chunk[1](error); -/******/ } -/******/ installedChunks[chunkId] = undefined; -/******/ } -/******/ }; -/******/ var timeout = setTimeout(function(){ -/******/ onScriptComplete({ type: 'timeout', target: script }); -/******/ }, 120000); -/******/ script.onerror = script.onload = onScriptComplete; -/******/ document.head.appendChild(script); -/******/ } -/******/ } -/******/ return Promise.all(promises); -/******/ }; -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ // on error function for async loading -/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; }; -/******/ -/******/ var jsonpArray = window["webpackJsonp"] = window["webpackJsonp"] || []; -/******/ var oldJsonpFunction = jsonpArray.push.bind(jsonpArray); -/******/ jsonpArray.push = webpackJsonpCallback; -/******/ jsonpArray = jsonpArray.slice(); -/******/ for(var i = 0; i < jsonpArray.length; i++) webpackJsonpCallback(jsonpArray[i]); -/******/ var parentJsonpFunction = oldJsonpFunction; -/******/ -/******/ -/******/ // run deferred modules from other chunks -/******/ checkDeferredModules(); -/******/ }) -/************************************************************************/ -/******/ ([]); \ No newline at end of file diff --git a/test/cases/split-chunks-all/expected/webpack-4/styles~a~b.css b/test/cases/split-chunks-all/expected/webpack-4/styles~a~b.css deleted file mode 100644 index cebc5c1c..00000000 --- a/test/cases/split-chunks-all/expected/webpack-4/styles~a~b.css +++ /dev/null @@ -1,4 +0,0 @@ -body { - background: red; -} - diff --git a/test/cases/split-chunks-all/webpack.config.js b/test/cases/split-chunks-all/webpack.config.js index e9edc39b..e19df414 100644 --- a/test/cases/split-chunks-all/webpack.config.js +++ b/test/cases/split-chunks-all/webpack.config.js @@ -1,5 +1,3 @@ -import webpack from 'webpack'; - import Self from '../../../src'; module.exports = { @@ -18,17 +16,11 @@ module.exports = { optimization: { splitChunks: { cacheGroups: { - styles: - webpack.version[0] === '4' - ? { - chunks: 'all', - enforce: true, - } - : { - type: 'css/mini-extract', - chunks: 'all', - enforce: true, - }, + styles: { + type: 'css/mini-extract', + chunks: 'all', + enforce: true, + }, }, }, }, diff --git a/test/emit-option.test.js b/test/emit-option.test.js index 6015dbbb..2ecd8f84 100644 --- a/test/emit-option.test.js +++ b/test/emit-option.test.js @@ -172,212 +172,204 @@ describe('emit option', () => { } } - if (webpack.version[0] !== '4') { - const outputPath = path.resolve(__dirname, './js/cache-memory'); - const webpackConfig = { - mode: 'development', - context: path.resolve(__dirname, './fixtures'), - cache: { - type: 'memory', - }, - entry: './locals.js', - output: { - publicPath: '', - path: outputPath, - }, - module: { - rules: [ - { - test: /\.css$/, - use: [ - { - loader: MiniCssExtractPlugin.loader, - options: { - emit: false, - }, + const outputPath = path.resolve(__dirname, './js/cache-memory'); + const webpackConfig = { + mode: 'development', + context: path.resolve(__dirname, './fixtures'), + cache: { + type: 'memory', + }, + entry: './locals.js', + output: { + publicPath: '', + path: outputPath, + }, + module: { + rules: [ + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + options: { + emit: false, }, - { - loader: 'css-loader', - options: { - modules: true, - }, + }, + { + loader: 'css-loader', + options: { + modules: true, }, - ], - }, - ], - }, - plugins: [ - new MiniCssExtractPlugin({ - filename: '[name].css', - }), - new AssetsModifyPlugin({ - file: modifyAsset, - }), + }, + ], + }, ], - }; - - await del([outputPath]); - - const compiler1 = webpack(webpackConfig); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect( - Object.keys(stats.compilation.assets).sort() - ).toMatchSnapshot(`assets`); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchSnapshot(`emittedAssets`); - runInJsDom('main.js', compiler1, stats, (dom) => { - expect(dom.serialize()).toMatchSnapshot('DOM'); - }); - expect(getWarnings(stats)).toMatchSnapshot('warnings'); - expect(getErrors(stats)).toMatchSnapshot('errors'); - - resolve(); + }, + plugins: [ + new MiniCssExtractPlugin({ + filename: '[name].css', + }), + new AssetsModifyPlugin({ + file: modifyAsset, + }), + ], + }; + + await del([outputPath]); + + const compiler1 = webpack(webpackConfig); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()).toMatchSnapshot( + `assets` + ); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchSnapshot(`emittedAssets`); + runInJsDom('main.js', compiler1, stats, (dom) => { + expect(dom.serialize()).toMatchSnapshot('DOM'); }); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + + resolve(); }); }); + }); - const compiler2 = webpack(webpackConfig); - - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler2.close(() => { - expect( - Object.keys(stats.compilation.assets).sort() - ).toMatchSnapshot(`assets`); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchSnapshot(`emittedAssets`); - runInJsDom('main.js', compiler2, stats, (dom) => { - expect(dom.serialize()).toMatchSnapshot('DOM'); - }); - expect(getWarnings(stats)).toMatchSnapshot('warnings'); - expect(getErrors(stats)).toMatchSnapshot('errors'); - - resolve(); + const compiler2 = webpack(webpackConfig); + + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()).toMatchSnapshot( + `assets` + ); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchSnapshot(`emittedAssets`); + runInJsDom('main.js', compiler2, stats, (dom) => { + expect(dom.serialize()).toMatchSnapshot('DOM'); }); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + + resolve(); }); }); + }); - fs.writeFileSync(modifyAsset, modifyAssetContent); - } else { - expect(true).toBe(true); - } + fs.writeFileSync(modifyAsset, modifyAssetContent); }); it('should work with the "memory" cache and disabled "emit" option', async () => { - if (webpack.version[0] !== '4') { - const outputPath = path.resolve(__dirname, './js/cache-memory'); - const webpackConfig = { - mode: 'development', - context: path.resolve(__dirname, 'fixtures'), - cache: { - type: 'memory', - }, - output: { - path: outputPath, - }, - entry: './style-url.js', - module: { - rules: [ - { - test: /\.css$/, - use: [ - { - loader: MiniCssExtractPlugin.loader, - options: { - publicPath: '', - emit: false, - }, + const outputPath = path.resolve(__dirname, './js/cache-memory'); + const webpackConfig = { + mode: 'development', + context: path.resolve(__dirname, 'fixtures'), + cache: { + type: 'memory', + }, + output: { + path: outputPath, + }, + entry: './style-url.js', + module: { + rules: [ + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + options: { + publicPath: '', + emit: false, }, - 'css-loader', - ], - }, - { - test: /\.svg$/, - type: 'asset/resource', - generator: { - filename: 'static/[name][ext][query]', }, + 'css-loader', + ], + }, + { + test: /\.svg$/, + type: 'asset/resource', + generator: { + filename: 'static/[name][ext][query]', }, - ], - }, - plugins: [ - new MiniCssExtractPlugin({ - filename: '[name].css', - }), + }, ], - }; - - await del([outputPath]); - - const compiler1 = webpack(webpackConfig); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect( - Object.keys(stats.compilation.assets).sort() - ).toMatchSnapshot(`assets`); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchSnapshot(`emittedAssets`); - expect(getWarnings(stats)).toMatchSnapshot('warnings'); - expect(getErrors(stats)).toMatchSnapshot('errors'); - - resolve(); - }); + }, + plugins: [ + new MiniCssExtractPlugin({ + filename: '[name].css', + }), + ], + }; + + await del([outputPath]); + + const compiler1 = webpack(webpackConfig); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()).toMatchSnapshot( + `assets` + ); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchSnapshot(`emittedAssets`); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + + resolve(); }); }); + }); - const compiler2 = webpack(webpackConfig); + const compiler2 = webpack(webpackConfig); - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); - return; - } + return; + } - compiler2.close(() => { - expect( - Object.keys(stats.compilation.assets).sort() - ).toMatchSnapshot(`assets`); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchSnapshot(`emittedAssets`); - expect(getWarnings(stats)).toMatchSnapshot('warnings'); - expect(getErrors(stats)).toMatchSnapshot('errors'); - - resolve(); - }); + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()).toMatchSnapshot( + `assets` + ); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchSnapshot(`emittedAssets`); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + + resolve(); }); }); - } else { - expect(true).toBe(true); - } + }); }); it('should invalidate the cache with disabled "emit" option', async () => { @@ -398,109 +390,105 @@ describe('emit option', () => { } } - if (webpack.version[0] !== '4') { - const outputPath = path.resolve(__dirname, './js/cache-memory'); - const modifyAsset = path.resolve(__dirname, 'fixtures', 'style-url.css'); - const modifyAssetContent = fs.readFileSync(modifyAsset); - const webpackConfig = { - mode: 'development', - context: path.resolve(__dirname, 'fixtures'), - cache: { - type: 'memory', - }, - output: { - path: outputPath, - }, - entry: './style-url.js', - module: { - rules: [ - { - test: /\.css$/, - use: [ - { - loader: MiniCssExtractPlugin.loader, - options: { - publicPath: '', - emit: false, - }, + const outputPath = path.resolve(__dirname, './js/cache-memory'); + const modifyAsset = path.resolve(__dirname, 'fixtures', 'style-url.css'); + const modifyAssetContent = fs.readFileSync(modifyAsset); + const webpackConfig = { + mode: 'development', + context: path.resolve(__dirname, 'fixtures'), + cache: { + type: 'memory', + }, + output: { + path: outputPath, + }, + entry: './style-url.js', + module: { + rules: [ + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + options: { + publicPath: '', + emit: false, }, - 'css-loader', - ], - }, - { - test: /\.svg$/, - type: 'asset/resource', - generator: { - filename: 'static/[name][ext][query]', }, + 'css-loader', + ], + }, + { + test: /\.svg$/, + type: 'asset/resource', + generator: { + filename: 'static/[name][ext][query]', }, - ], - }, - plugins: [ - new MiniCssExtractPlugin({ - filename: '[name].css', - }), - new AssetsModifyPlugin({ - file: modifyAsset, - }), + }, ], - }; - - await del([outputPath]); - - const compiler1 = webpack(webpackConfig); - - await new Promise((resolve, reject) => { - compiler1.run((error, stats) => { - if (error) { - reject(error); - - return; - } - - compiler1.close(() => { - expect( - Object.keys(stats.compilation.assets).sort() - ).toMatchSnapshot(`assets`); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchSnapshot(`emittedAssets`); - expect(getWarnings(stats)).toMatchSnapshot('warnings'); - expect(getErrors(stats)).toMatchSnapshot('errors'); - - resolve(); - }); + }, + plugins: [ + new MiniCssExtractPlugin({ + filename: '[name].css', + }), + new AssetsModifyPlugin({ + file: modifyAsset, + }), + ], + }; + + await del([outputPath]); + + const compiler1 = webpack(webpackConfig); + + await new Promise((resolve, reject) => { + compiler1.run((error, stats) => { + if (error) { + reject(error); + + return; + } + + compiler1.close(() => { + expect(Object.keys(stats.compilation.assets).sort()).toMatchSnapshot( + `assets` + ); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchSnapshot(`emittedAssets`); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + + resolve(); }); }); + }); - const compiler2 = webpack(webpackConfig); + const compiler2 = webpack(webpackConfig); - await new Promise((resolve, reject) => { - compiler2.run((error, stats) => { - if (error) { - reject(error); + await new Promise((resolve, reject) => { + compiler2.run((error, stats) => { + if (error) { + reject(error); - return; - } + return; + } - compiler2.close(() => { - expect( - Object.keys(stats.compilation.assets).sort() - ).toMatchSnapshot(`assets`); - expect( - Array.from(stats.compilation.emittedAssets).sort() - ).toMatchSnapshot(`emittedAssets`); - expect(getWarnings(stats)).toMatchSnapshot('warnings'); - expect(getErrors(stats)).toMatchSnapshot('errors'); - - resolve(); - }); + compiler2.close(() => { + expect(Object.keys(stats.compilation.assets).sort()).toMatchSnapshot( + `assets` + ); + expect( + Array.from(stats.compilation.emittedAssets).sort() + ).toMatchSnapshot(`emittedAssets`); + expect(getWarnings(stats)).toMatchSnapshot('warnings'); + expect(getErrors(stats)).toMatchSnapshot('errors'); + + resolve(); }); }); + }); - fs.writeFileSync(modifyAsset, modifyAssetContent); - } else { - expect(true).toBe(true); - } + fs.writeFileSync(modifyAsset, modifyAssetContent); }); }); diff --git a/test/enforce-esm.test.js b/test/enforce-esm.test.js index 03de4d19..86b54af1 100644 --- a/test/enforce-esm.test.js +++ b/test/enforce-esm.test.js @@ -1,9 +1,5 @@ -import webpack from 'webpack'; - import { getCompiler, source, compile } from './helpers'; -const isWebpack4 = webpack.version[0] === '4'; - it('should enforce esm for empty module without options.esModule', async () => { expect.assertions(3); @@ -20,7 +16,7 @@ it('should enforce esm for empty module without options.esModule', async () => { const { modules } = stats.toJson({ all: false, modules: true }); expect( modules.filter((m) => m.moduleType !== 'runtime' && !m.orphan).length - ).toBe(isWebpack4 ? 1 : 2); + ).toBe(2); expect(source('./simple.css', stats)).toMatchInlineSnapshot(` "// extracted by mini-css-extract-plugin export {};" @@ -43,7 +39,7 @@ it('should enforce esm for empty module with options.esModule', async () => { const { modules } = stats.toJson({ all: false, modules: true }); expect( modules.filter((m) => m.moduleType !== 'runtime' && !m.orphan).length - ).toBe(isWebpack4 ? 1 : 2); + ).toBe(2); expect(source('./simple.css', stats)).toMatchInlineSnapshot(` "// extracted by mini-css-extract-plugin export {};" diff --git a/test/helpers/getCompiler.js b/test/helpers/getCompiler.js index 0b4b03df..257a80f9 100644 --- a/test/helpers/getCompiler.js +++ b/test/helpers/getCompiler.js @@ -32,29 +32,13 @@ export default (fixture, loaderOptions = {}, config = {}) => { }, ], }, - ].concat( - webpack.version[0] !== '4' - ? { - test: /\.svg$/, - type: 'asset/resource', - generator: { - filename: '[name][ext]', - }, - } - : [ - { - test: /\.svg$/i, - rules: [ - { - loader: 'file-loader', - options: { - name: '[name].[ext]', - }, - }, - ], - }, - ] - ), + ].concat({ + test: /\.svg$/, + type: 'asset/resource', + generator: { + filename: '[name][ext]', + }, + }), }, plugins: [ new MiniCssExtractPlugin({ @@ -70,11 +54,7 @@ export default (fixture, loaderOptions = {}, config = {}) => { const compiler = webpack(fullConfig); if (!outputFileSystem) { - const outputFS = createFsFromVolume(new Volume()); - // Todo remove when we drop webpack@4 support - outputFS.join = path.join.bind(path); - - compiler.outputFileSystem = outputFS; + compiler.outputFileSystem = createFsFromVolume(new Volume()); } else { compiler.outputFileSystem = outputFileSystem; } diff --git a/test/helpers/snapshotResolver.js b/test/helpers/snapshotResolver.js deleted file mode 100644 index bb368528..00000000 --- a/test/helpers/snapshotResolver.js +++ /dev/null @@ -1,34 +0,0 @@ -const path = require('path'); - -const webpack = require('webpack'); - -// eslint-disable-next-line global-require -const [webpackVersion] = webpack.version; -const snapshotExtension = `.snap.webpack${webpackVersion}`; - -// eslint-disable-next-line no-console -console.log( - 'Current webpack version:', - webpackVersion, - process.env.EXPERIMENTAL_USE_IMPORT_MODULE - ? '(experimental use importModule)' - : '' -); - -module.exports = { - resolveSnapshotPath: (testPath) => - path.join( - path.dirname(testPath), - '__snapshots__', - `${path.basename(testPath)}${snapshotExtension}` - ), - resolveTestPath: (snapshotPath) => - snapshotPath - .replace(`${path.sep}__snapshots__`, '') - .slice(0, -snapshotExtension.length), - testPathForConsistencyCheck: path.join( - 'consistency_check', - '__tests__', - 'example.test.js' - ), -}; diff --git a/test/validate-plugin-options.test.js b/test/validate-plugin-options.test.js index 0638f4a8..bc4890ec 100644 --- a/test/validate-plugin-options.test.js +++ b/test/validate-plugin-options.test.js @@ -1,5 +1,3 @@ -import { version as webpackVersion } from 'webpack'; - import MiniCssExtractPlugin from '../src'; describe('validate options', () => { @@ -12,12 +10,7 @@ describe('validate options', () => { failure: [true], }, chunkFilename: { - success: [ - '[id].css', - webpackVersion[0] === '4' - ? '[id].[name].css' - : ({ chunk }) => `${chunk.id}.${chunk.name}.css`, - ], + success: ['[id].css', ({ chunk }) => `${chunk.id}.${chunk.name}.css`], failure: [true], }, ignoreOrder: {