Unverified Commit dab55b47 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add serialization for mini-css-plugin webpack 5 caching (#16379)

parent 8efc8be3
...@@ -33,6 +33,7 @@ export function getClientStyleLoader({ ...@@ -33,6 +33,7 @@ export function getClientStyleLoader({
}, },
} }
: { : {
// @ts-ignore: TODO: remove when webpack 5 is stable
loader: MiniCssExtractPlugin.loader, loader: MiniCssExtractPlugin.loader,
options: { publicPath: `${assetPrefix}/_next/` }, options: { publicPath: `${assetPrefix}/_next/` },
} }
......
import MiniCssExtractPlugin from 'mini-css-extract-plugin' // @ts-ignore: TODO: remove when webpack 5 is stable
import MiniCssExtractPlugin from './mini-css-extract-plugin/src'
export default class NextMiniCssExtractPlugin extends MiniCssExtractPlugin { export default class NextMiniCssExtractPlugin extends MiniCssExtractPlugin {
__next_css_remove = true __next_css_remove = true
......
Copyright JS Foundation and other contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import webpack from 'webpack'
class CssDependency extends webpack.Dependency {
constructor(
{ identifier, content, media, sourceMap },
context,
identifierIndex
) {
super()
this.identifier = identifier
this.identifierIndex = identifierIndex
this.content = content
this.media = media
this.sourceMap = sourceMap
this.context = context
}
getResourceIdentifier() {
return `css-module-${this.identifier}-${this.identifierIndex}`
}
}
const isWebpack5 = parseInt(webpack.version) === 5
if (isWebpack5) {
// @ts-ignore TODO: remove ts-ignore when webpack 5 is stable
webpack.util.serialization.register(
CssDependency,
'next/dist/build/webpack/plugins/mini-css-extract-plugin/src/CssDependency',
null,
{
serialize(obj, { write }) {
write(obj.identifier)
write(obj.content)
write(obj.media)
write(obj.sourceMap)
write(obj.context)
write(obj.identifierIndex)
},
deserialize({ read }) {
const obj = new CssDependency(
{
identifier: read(),
content: read(),
media: read(),
sourceMap: read(),
},
read(),
read()
)
return obj
},
}
)
}
export default CssDependency
import webpack from 'webpack'
class CssModule extends webpack.Module {
constructor(dependency) {
super('css/mini-extract', dependency.context)
this.id = ''
this._identifier = dependency.identifier
this._identifierIndex = dependency.identifierIndex
this.content = dependency.content
this.media = dependency.media
this.sourceMap = dependency.sourceMap
} // no source() so webpack doesn't do add stuff to the bundle
size() {
return this.content.length
}
identifier() {
return `css ${this._identifier} ${this._identifierIndex}`
}
readableIdentifier(requestShortener) {
return `css ${requestShortener.shorten(this._identifier)}${
this._identifierIndex ? ` (${this._identifierIndex})` : ''
}`
}
nameForCondition() {
const resource = this._identifier.split('!').pop()
const idx = resource.indexOf('?')
if (idx >= 0) {
return resource.substring(0, idx)
}
return resource
}
updateCacheModule(module) {
this.content = module.content
this.media = module.media
this.sourceMap = module.sourceMap
}
needRebuild() {
return true
}
build(options, compilation, resolver, fileSystem, callback) {
this.buildInfo = {}
this.buildMeta = {}
callback()
}
updateHash(hash) {
super.updateHash(hash)
hash.update(this.content)
hash.update(this.media || '')
hash.update(this.sourceMap ? JSON.stringify(this.sourceMap) : '')
}
}
const isWebpack5 = parseInt(webpack.version) === 5
if (isWebpack5) {
// @ts-ignore TODO: remove ts-ignore when webpack 5 is stable
webpack.util.serialization.register(
CssModule,
'next/dist/build/webpack/plugins/mini-css-extract-plugin/src/CssModule',
null,
{
serialize(obj, { write }) {
write(obj.context)
write(obj._identifier)
write(obj._identifierIndex)
write(obj.content)
write(obj.media)
write(obj.sourceMap)
},
deserialize({ read }) {
const obj = new CssModule({
context: read(),
identifier: read(),
identifierIndex: read(),
content: read(),
media: read(),
sourceMap: read(),
})
return obj
},
}
)
}
export default CssModule
import NativeModule from 'module'
import loaderUtils from 'loader-utils'
import webpack from 'webpack'
import NodeTargetPlugin from 'webpack/lib/node/NodeTargetPlugin'
import CssDependency from './CssDependency'
const pluginName = 'mini-css-extract-plugin'
function evalModuleCode(loaderContext, code, filename) {
const module = new NativeModule(filename, loaderContext)
module.paths = NativeModule._nodeModulePaths(loaderContext.context) // eslint-disable-line no-underscore-dangle
module.filename = filename
module._compile(code, filename) // eslint-disable-line no-underscore-dangle
return module.exports
}
function findModuleById(modules, id) {
for (const module of modules) {
if (module.id === id) {
return module
}
}
return null
}
export function pitch(request) {
const options = loaderUtils.getOptions(this) || {}
const loaders = this.loaders.slice(this.loaderIndex + 1)
this.addDependency(this.resourcePath)
const childFilename = '*'
const publicPath =
typeof options.publicPath === 'string'
? options.publicPath === '' || options.publicPath.endsWith('/')
? options.publicPath
: `${options.publicPath}/`
: typeof options.publicPath === 'function'
? options.publicPath(this.resourcePath, this.rootContext)
: this._compilation.outputOptions.publicPath
const outputOptions = {
filename: childFilename,
publicPath,
}
const childCompiler = this._compilation.createChildCompiler(
`${pluginName} ${request}`,
outputOptions
)
new webpack.node.NodeTemplatePlugin(outputOptions).apply(childCompiler)
new webpack.LibraryTemplatePlugin(null, 'commonjs2').apply(childCompiler)
new NodeTargetPlugin().apply(childCompiler)
new webpack.SingleEntryPlugin(this.context, `!!${request}`, pluginName).apply(
childCompiler
)
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }).apply(
childCompiler
)
childCompiler.hooks.thisCompilation.tap(
`${pluginName} loader`,
(compilation) => {
compilation.hooks.normalModuleLoader.tap(
`${pluginName} loader`,
(loaderContext, module) => {
// eslint-disable-next-line no-param-reassign
loaderContext.emitFile = this.emitFile
if (module.request === request) {
// eslint-disable-next-line no-param-reassign
module.loaders = loaders.map((loader) => {
return {
loader: loader.path,
options: loader.options,
ident: loader.ident,
}
})
}
}
)
}
)
let source
childCompiler.hooks.afterCompile.tap(pluginName, (compilation) => {
source =
compilation.assets[childFilename] &&
compilation.assets[childFilename].source()
// Remove all chunk assets
compilation.chunks.forEach((chunk) => {
chunk.files.forEach((file) => {
delete compilation.assets[file] // eslint-disable-line no-param-reassign
})
})
})
const callback = this.async()
childCompiler.runAsChild((err, entries, compilation) => {
const addDependencies = (dependencies) => {
if (!Array.isArray(dependencies) && dependencies != null) {
throw new Error(
`Exported value was not extracted as an array: ${JSON.stringify(
dependencies
)}`
)
}
const identifierCountMap = new Map()
for (const dependency of dependencies) {
const count = identifierCountMap.get(dependency.identifier) || 0
this._module.addDependency(
new CssDependency(dependency, dependency.context, count)
)
identifierCountMap.set(dependency.identifier, count + 1)
}
}
if (err) {
return callback(err)
}
if (compilation.errors.length > 0) {
return callback(compilation.errors[0])
}
compilation.fileDependencies.forEach((dep) => {
this.addDependency(dep)
}, this)
compilation.contextDependencies.forEach((dep) => {
this.addContextDependency(dep)
}, this)
if (!source) {
return callback(new Error("Didn't get a result from child compiler"))
}
let locals
try {
let dependencies
let exports = evalModuleCode(this, source, request)
// eslint-disable-next-line no-underscore-dangle
exports = exports.__esModule ? exports.default : exports
locals = exports && exports.locals
if (!Array.isArray(exports)) {
dependencies = [[null, exports]]
} else {
dependencies = exports.map(([id, content, media, sourceMap]) => {
const module = findModuleById(compilation.modules, id)
return {
identifier: module.identifier(),
context: module.context,
content,
media,
sourceMap,
}
})
}
addDependencies(dependencies)
} catch (e) {
return callback(e)
}
const esModule =
typeof options.esModule !== 'undefined' ? options.esModule : false
const result = locals
? `\n${esModule ? 'export default' : 'module.exports ='} ${JSON.stringify(
locals
)};`
: esModule
? `\nexport {};`
: ''
let resultSource = `// extracted by ${pluginName}`
resultSource += result
return callback(null, resultSource)
})
}
export default function () {}
...@@ -26,6 +26,7 @@ import webpack, { ...@@ -26,6 +26,7 @@ import webpack, {
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
compilation as CompilationType, compilation as CompilationType,
} from 'webpack' } from 'webpack'
import sources from 'webpack-sources'
const isWebpack5 = parseInt(webpack.version!) === 5 const isWebpack5 = parseInt(webpack.version!) === 5
...@@ -108,15 +109,10 @@ export class ReactLoadablePlugin { ...@@ -108,15 +109,10 @@ export class ReactLoadablePlugin {
createAssets(compiler: any, compilation: any, assets: any) { createAssets(compiler: any, compilation: any, assets: any) {
const manifest = buildManifest(compiler, compilation) const manifest = buildManifest(compiler, compilation)
var json = JSON.stringify(manifest, null, 2) // @ts-ignore: TODO: remove when webpack 5 is stable
assets[this.filename] = { assets[this.filename] = new (webpack.sources || sources).RawSource(
source() { JSON.stringify(manifest, null, 2)
return json )
},
size() {
return json.length
},
}
return assets return assets
} }
......
...@@ -94,7 +94,6 @@ ...@@ -94,7 +94,6 @@
"find-cache-dir": "3.3.1", "find-cache-dir": "3.3.1",
"jest-worker": "24.9.0", "jest-worker": "24.9.0",
"loader-utils": "2.0.0", "loader-utils": "2.0.0",
"mini-css-extract-plugin": "0.8.0",
"mkdirp": "0.5.3", "mkdirp": "0.5.3",
"native-url": "0.3.4", "native-url": "0.3.4",
"neo-async": "2.6.1", "neo-async": "2.6.1",
......
...@@ -11572,15 +11572,6 @@ min-indent@^1.0.0: ...@@ -11572,15 +11572,6 @@ min-indent@^1.0.0:
resolved "https://registry.yarnpkg.com/min-indent/-/min-indent-1.0.1.tgz#a63f681673b30571fbe8bc25686ae746eefa9869" resolved "https://registry.yarnpkg.com/min-indent/-/min-indent-1.0.1.tgz#a63f681673b30571fbe8bc25686ae746eefa9869"
integrity sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg== integrity sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==
mini-css-extract-plugin@0.8.0:
version "0.8.0"
resolved "https://registry.yarnpkg.com/mini-css-extract-plugin/-/mini-css-extract-plugin-0.8.0.tgz#81d41ec4fe58c713a96ad7c723cdb2d0bd4d70e1"
dependencies:
loader-utils "^1.1.0"
normalize-url "1.9.1"
schema-utils "^1.0.0"
webpack-sources "^1.1.0"
minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1: minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1:
version "1.0.1" version "1.0.1"
resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7" resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7"
...@@ -12058,7 +12049,7 @@ normalize-range@^0.1.2: ...@@ -12058,7 +12049,7 @@ normalize-range@^0.1.2:
version "0.1.2" version "0.1.2"
resolved "https://registry.yarnpkg.com/normalize-range/-/normalize-range-0.1.2.tgz#2d10c06bdfd312ea9777695a4d28439456b75942" resolved "https://registry.yarnpkg.com/normalize-range/-/normalize-range-0.1.2.tgz#2d10c06bdfd312ea9777695a4d28439456b75942"
normalize-url@1.9.1, normalize-url@^1.4.0: normalize-url@^1.4.0:
version "1.9.1" version "1.9.1"
resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-1.9.1.tgz#2cc0d66b31ea23036458436e3620d85954c66c3c" resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-1.9.1.tgz#2cc0d66b31ea23036458436e3620d85954c66c3c"
dependencies: dependencies:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment