Unverified Commit 5f3351db authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

use official mini-css-extract-plugin and experimentalUseImportModule (#24573)



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.

## Documentation / Examples

- [ ] Make sure the linting passes
parent 9a0fc42d
import curry from 'next/dist/compiled/lodash.curry'
import path from 'path'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import { webpack, isWebpack5 } from 'next/dist/compiled/webpack/webpack'
import MiniCssExtractPlugin from '../../../plugins/mini-css-extract-plugin'
import { loader, plugin } from '../../helpers'
import { ConfigurationContext, ConfigurationFn, pipe } from '../../utils'
......@@ -14,7 +14,7 @@ import {
import { getPostCssPlugins } from './plugins'
// RegExps for all Style Sheet variants
const regexLikeCss = /\.(css|scss|sass)$/
const regexLikeCss = /\.(css|scss|sass)(\.webpack\[javascript\/auto\])?$/
// RegExps for Style Sheets
const regexCssGlobal = /(?<!\.module)\.css$/
......@@ -292,7 +292,12 @@ export const css = curry(async function css(
// This should only be applied to CSS files
issuer: regexLikeCss,
// Exclude extensions that webpack handles by default
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
exclude: [
/\.(js|mjs|jsx|ts|tsx)$/,
/\.html$/,
/\.json$/,
/\.webpack\[[^\]]+\]$/,
],
use: {
// `file-loader` always emits a URL reference, where `url-loader`
// might inline the asset as a data URI
......@@ -314,6 +319,7 @@ export const css = curry(async function css(
plugin(
// @ts-ignore webpack 5 compat
new MiniCssExtractPlugin({
experimentalUseImportModule: isWebpack5,
filename: 'static/css/[contenthash].css',
chunkFilename: 'static/css/[contenthash].css',
// Next.js guarantees that CSS order "doesn't matter", due to imposed
......
......@@ -35,6 +35,6 @@ export function getClientStyleLoader({
: {
// @ts-ignore: TODO: remove when webpack 5 is stable
loader: MiniCssExtractPlugin.loader,
options: { publicPath: `${assetPrefix}/_next/` },
options: { publicPath: `${assetPrefix}/_next/`, esModule: false },
}
}
// @ts-ignore: TODO: remove when webpack 5 is stable
import MiniCssExtractPlugin from './mini-css-extract-plugin/src'
import MiniCssExtractPlugin from 'next/dist/compiled/mini-css-extract-plugin'
export default class NextMiniCssExtractPlugin extends MiniCssExtractPlugin {
__next_css_remove = true
......
import {
webpack,
onWebpackInit,
isWebpack5,
} from 'next/dist/compiled/webpack/webpack'
let CssDependency
onWebpackInit(function () {
CssDependency = class 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}`
}
}
// @ts-ignore TODO: remove ts-ignore when webpack 5 is stable
if (isWebpack5) {
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 { CssDependency as default }
import {
webpack,
onWebpackInit,
isWebpack5,
} from 'next/dist/compiled/webpack/webpack'
let CssModule
onWebpackInit(function () {
CssModule = class 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, context) {
super.updateHash(hash, context)
hash.update(this.content)
hash.update(this.media || '')
hash.update(this.sourceMap ? JSON.stringify(this.sourceMap) : '')
}
}
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 { CssModule as default }
import NativeModule from 'module'
import loaderUtils from 'next/dist/compiled/loader-utils'
import {
webpack,
isWebpack5,
NodeTargetPlugin,
} from 'next/dist/compiled/webpack/webpack'
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 getModuleId(compilation, module) {
if (isWebpack5) {
return compilation.chunkGraph.getModuleId(module)
}
return module.id
}
function findModuleById(compilation, id) {
for (const module of compilation.modules) {
if (getModuleId(compilation, module) === 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,
library: {
type: 'commonjs2',
name: null,
},
}
const childCompiler = this._compilation.createChildCompiler(
`${pluginName} ${request}`,
outputOptions
)
new webpack.node.NodeTemplatePlugin(outputOptions).apply(childCompiler)
if (isWebpack5) {
new webpack.library.EnableLibraryPlugin(outputOptions.library.type).apply(
childCompiler
)
} else {
new webpack.LibraryTemplatePlugin(null, 'commonjs2').apply(childCompiler)
}
new NodeTargetPlugin().apply(childCompiler)
new (isWebpack5 ? webpack.EntryPlugin : webpack.SingleEntryPlugin)(
this.context,
`!!${request}`,
pluginName
).apply(childCompiler)
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }).apply(
childCompiler
)
let source
childCompiler.hooks.thisCompilation.tap(
`${pluginName} loader`,
(compilation) => {
const hook = isWebpack5
? webpack.NormalModule.getCompilationHooks(compilation).loader
: compilation.hooks.normalModuleLoader
hook.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,
}
})
}
})
if (isWebpack5) {
compilation.hooks.processAssets.tap(
{
name: pluginName,
// @ts-ignore TODO: Remove ignore when webpack 5 is stable
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
},
(assets) => {
source = assets[childFilename] && assets[childFilename].source()
// Remove all chunk assets
Object.keys(assets).forEach((file) => delete assets[file])
}
)
}
}
)
// webpack 5 case is covered in hooks.thisCompilation above
if (!isWebpack5) {
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, 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 () {}
......@@ -7,6 +7,14 @@ module.exports = function () {
NodeTargetPlugin: require('webpack/lib/node/NodeTargetPlugin'),
ModuleFilenameHelpers: require('webpack/lib/ModuleFilenameHelpers'),
GraphHelpers: require('webpack/lib/GraphHelpers'),
Module: require('webpack/lib/Module'),
NormalModule: require('webpack/lib/NormalModule'),
Dependency: require('webpack/lib/Dependency'),
LibraryTemplatePlugin: require('webpack/lib/LibraryTemplatePlugin'),
SingleEntryPlugin: require('webpack/lib/SingleEntryPlugin'),
node: require('webpack').node,
util: require('webpack').util,
optimize: require('webpack').optimize,
sources: require('webpack-sources'),
webpack: require('webpack'),
package: {
......
......@@ -6,6 +6,7 @@ module.exports = function () {
ModuleFilenameHelpers: require('webpack5/lib/ModuleFilenameHelpers'),
NodeTargetPlugin: require('webpack5/lib/node/NodeTargetPlugin'),
StringXor: require('webpack5/lib/util/StringXor'),
NormalModule: require('webpack/lib/NormalModule'),
sources: require('webpack5').sources,
webpack: require('webpack5'),
}
......
module.exports = require('./webpack.js').NormalModule
......@@ -21,13 +21,14 @@ 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 stripAnsi from 'next/dist/compiled/strip-ansi'
// This file is based on https://github.com/facebook/create-react-app/blob/7b1a32be6ec9f99a6c9a3c66813f3ac09c4736b9/packages/react-dev-utils/formatWebpackMessages.js
// It's been edited to remove chalk and CRA-specific logic
const friendlySyntaxErrorLabel = 'Syntax error:'
function isLikelyASyntaxError(message) {
return message.indexOf(friendlySyntaxErrorLabel) !== -1
return stripAnsi(message).indexOf(friendlySyntaxErrorLabel) !== -1
}
// Cleans up webpack error messages.
......@@ -35,8 +36,8 @@ function formatMessage(message) {
// TODO: Replace this once webpack 5 is stable
if (typeof message === 'object' && message.message) {
message =
(message.moduleName ? message.moduleName + '\n' : '') +
(message.file ? message.file + '\n' : '') +
(message.moduleName ? stripAnsi(message.moduleName) + '\n' : '') +
(message.file ? stripAnsi(message.file) + '\n' : '') +
message.message
}
let lines = message.split('\n')
......@@ -84,7 +85,7 @@ function formatMessage(message) {
lines.splice(1, 1)
}
// Clean up file name
lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1')
lines[0] = lines[0].replace(/^(.*) \d+:\d+(?:-\d+)?$/, '$1')
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1] && lines[1].indexOf('Module not found: ') === 0) {
......
module.exports=(()=>{"use strict";var e={405:(e,r,_)=>{e.exports=_(612).default},612:e=>{e.exports=require("./index.js")}};var r={};function __nccwpck_require__(_){if(r[_]){return r[_].exports}var t=r[_]={exports:{}};var a=true;try{e[_](t,t.exports,__nccwpck_require__);a=false}finally{if(a)delete r[_]}return t.exports}__nccwpck_require__.ab=__dirname+"/";return __nccwpck_require__(405)})();
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
{"name":"mini-css-extract-plugin","main":"cjs.js","author":"Tobias Koppers @sokra","license":"MIT"}
module.exports = require('./webpack.js').NormalModule
......@@ -130861,6 +130861,14 @@ module.exports = function () {
NodeTargetPlugin: __webpack_require__(59743),
ModuleFilenameHelpers: __webpack_require__(71474),
GraphHelpers: __webpack_require__(32973),
Module: __webpack_require__(75993),
NormalModule: __webpack_require__(25963),
Dependency: __webpack_require__(57282),
LibraryTemplatePlugin: __webpack_require__(65237),
SingleEntryPlugin: __webpack_require__(19070),
node: __webpack_require__(92929).node,
util: __webpack_require__(92929).util,
optimize: __webpack_require__(92929).optimize,
sources: __webpack_require__(53665),
webpack: __webpack_require__(92929),
package: {
This diff is collapsed.
......@@ -220,6 +220,7 @@
"loader-utils": "2.0.0",
"lodash.curry": "4.1.1",
"lru-cache": "5.1.1",
"mini-css-extract-plugin": "1.5.0",
"nanoid": "3.1.20",
"neo-async": "2.6.1",
"ora": "4.0.4",
......
......@@ -617,6 +617,40 @@ export async function ncc_webpack_sources2(task, opts) {
.ncc({ packageName: 'webpack-sources2', externals, target: 'es5' })
.target('compiled/webpack-sources2')
}
// eslint-disable-next-line camelcase
externals['mini-css-extract-plugin'] =
'next/dist/compiled/mini-css-extract-plugin'
export async function ncc_mini_css_extract_plugin(task, opts) {
await task
.source(
relative(
__dirname,
resolve(require.resolve('mini-css-extract-plugin'), '../index.js')
)
)
.ncc({
externals: {
...externals,
'./index': './index.js',
'schema-utils': 'next/dist/compiled/schema-utils3',
},
})
.target('compiled/mini-css-extract-plugin')
await task
.source(
opts.src ||
relative(__dirname, require.resolve('mini-css-extract-plugin'))
)
.ncc({
packageName: 'mini-css-extract-plugin',
externals: {
...externals,
'./index': './index.js',
'schema-utils': 'next/dist/compiled/schema-utils3',
},
})
.target('compiled/mini-css-extract-plugin')
}
// eslint-disable-next-line camelcase
export async function ncc_webpack_bundle4(task, opts) {
......@@ -750,6 +784,7 @@ export async function ncc(task, opts) {
'ncc_webpack_bundle_packages',
'ncc_webpack_sources',
'ncc_webpack_sources2',
'ncc_mini_css_extract_plugin',
],
opts
)
......
......@@ -217,7 +217,7 @@ describe('CSS Modules: Importing Invalid Global CSS', () => {
})
expect(code).not.toBe(0)
expect(stderr).toContain('Failed to compile')
expect(stderr).toContain('pages/styles.module.css')
expect(stderr).toContain('pages/styles.css')
expect(stderr).toContain('Selector "a" is not pure')
})
})
......
......@@ -11035,6 +11035,15 @@ min-indent@^1.0.0:
resolved "https://registry.yarnpkg.com/min-indent/-/min-indent-1.0.1.tgz#a63f681673b30571fbe8bc25686ae746eefa9869"
integrity sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==
mini-css-extract-plugin@1.5.0:
version "1.5.0"
resolved "https://registry.yarnpkg.com/mini-css-extract-plugin/-/mini-css-extract-plugin-1.5.0.tgz#69bee3b273d2d4ee8649a2eb409514b7df744a27"
integrity sha512-SIbuLMv6jsk1FnLIU5OUG/+VMGUprEjM1+o2trOAx8i5KOKMrhyezb1dJ4Ugsykb8Jgq8/w5NEopy6escV9G7g==
dependencies:
loader-utils "^2.0.0"
schema-utils "^3.0.0"
webpack-sources "^1.1.0"
minimalistic-assert@^1.0.0, minimalistic-assert@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz#2e194de044626d4a10e7f7fbc00ce73e83e4d5c7"
......
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