Skip to content
This repository has been archived by the owner on Sep 13, 2022. It is now read-only.

Commit

Permalink
fix: 升级 webpack5 配置
Browse files Browse the repository at this point in the history
  • Loading branch information
virgoone committed Sep 19, 2021
1 parent 765c21c commit f9a1f2f
Show file tree
Hide file tree
Showing 7 changed files with 802 additions and 316 deletions.
17 changes: 9 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
},
"dependencies": {
"@babel/cli": "^7.15.4",
"@babel/core": "^7.15.4",
"@babel/core": "^7.15.5",
"@babel/plugin-proposal-class-properties": "^7.14.5",
"@babel/plugin-proposal-decorators": "^7.15.4",
"@babel/plugin-proposal-object-rest-spread": "^7.14.7",
Expand All @@ -57,24 +57,25 @@
"chalk": "^4.1.2",
"check-dependencies": "1.1.0",
"css-loader": "^6.2.0",
"css-minimizer-webpack-plugin": "^3.0.2",
"deepmerge": "4.2.2",
"fs-extra": "^10.0.0",
"html-webpack-plugin": "^5.3.2",
"less": "^4.1.1",
"less-loader": "^10.0.1",
"mini-css-extract-plugin": "^2.3.0",
"optimize-css-assets-webpack-plugin": "^6.0.1",
"postcss": "^8.3.6",
"postcss-flexbugs-fixes": "^5.0.2",
"postcss-loader": "^6.1.1",
"postcss-safe-parser": "^6.0.0",
"postcss-normalize": "^10.0.1",
"postcss-preset-env": "^6.7.0",
"react-dev-utils": "^11.0.4",
"resolve-url-loader": "^4.0.0",
"sass": "^1.41.1",
"sass-loader": "^12.1.0",
"script-ext-html-webpack-plugin": "^2.1.5",
"style-loader": "^3.2.1",
"terser-webpack-plugin": "^5.2.4",
"thread-loader": "^3.0.4",
"url-loader": "^4.1.1",
"webpack": "^5.52.1",
"webpack": "^5.53.0",
"webpack-chain": "^6.5.1",
"webpack-dev-server": "^4.2.1",
"webpack-merge": "^5.8.0",
Expand All @@ -88,7 +89,7 @@
"eslint-config-lark": "^0.1.2",
"husky": "^7.0.2",
"lint-staged": "^11.1.2",
"prettier": "^2.4.0",
"prettier": "^2.4.1",
"standard-version": "7.1.0",
"typescript": "^4.4.3"
}
Expand Down
41 changes: 34 additions & 7 deletions src/commands/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ if (!process.env.APP_ENV) {
}

process.on('unhandledRejection', (err) => {
console.error(err)
throw err
})

Expand All @@ -17,15 +18,19 @@ const chalk = require('chalk')
const formatWebpackMessages = require('react-dev-utils/formatWebpackMessages')
const FileSizeReporter = require('react-dev-utils/FileSizeReporter')
const printBuildError = require('react-dev-utils/printBuildError')
const { checkBrowsers } = require('react-dev-utils/browsersHelper')

const configFactory = require('../webpack/webpack.config.build')
const { appBuild, appPublic, appHtml } = require('../variables/paths')
const { appPath, appBuild, appPublic, appHtml } = require('../variables/paths')

const { measureFileSizesBeforeBuild, printFileSizesAfterBuild } =
FileSizeReporter

const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024

const isInteractive = process.stdout.isTTY

function build(previousFileSizes) {
console.log(`${chalk.green('Environment:')} ${process.env.APP_ENV}`)
console.log()
Expand All @@ -43,11 +48,22 @@ function build(previousFileSizes) {
if (!err.message) {
return reject(err)
}

let errMessage = err.message

// Add additional information for postcss errors
if (Object.prototype.hasOwnProperty.call(err, 'postcssNode')) {
errMessage += `\nCompileError: Begins at CSS selector ${err?.postcssNode?.selector}`
}

messages = formatWebpackMessages({
errors: [err.message],
errors: [errMessage],
warnings: []
})
} else {
console.error(
stats.toJson({ all: false, warnings: true, errors: true })
)
messages = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
)
Expand Down Expand Up @@ -94,7 +110,8 @@ function copyPublicFolder() {
}

module.exports = () => {
measureFileSizesBeforeBuild(appBuild)
checkBrowsers(appPath, isInteractive)
.then(() => measureFileSizesBeforeBuild(appBuild))
.then((previousFileSizes) => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
Expand Down Expand Up @@ -134,14 +151,24 @@ module.exports = () => {
console.log()
},
(err) => {
console.log(chalk.red('Failed to compile.\n'))
printBuildError(err)
process.exit(1)
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'
if (tscCompileOnError) {
console.log(
chalk.yellow(
'Compiled with the following type errors (you may want to check these before deploying your app):\n'
)
)
printBuildError(err)
} else {
console.log(chalk.red('Failed to compile.\n'))
printBuildError(err)
process.exit(1)
}
}
)
.catch((err) => {
if (err && err.message) {
console.log(err.message)
console.error(err.message)
}
process.exit(1)
})
Expand Down
8 changes: 6 additions & 2 deletions src/commands/start.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,13 @@ module.exports = async (defaultPort) => {
const config = configFactory()
const useTypeScript = fs.existsSync(appTsConfig)
const useYarn = fs.existsSync(yarnLockFile)
const tscCompileOnError = process.env.TSC_COMPILE_ON_ERROR === 'true'
const devSocket = {
warnings: (warnings) =>
devServer.sockWrite(devServer.sockets, 'warnings', warnings),
errors: (errors) =>
errors: (errors) => {
devServer.sockWrite(devServer.sockets, 'errors', errors)
}
}
const compiler = createCompiler({
appName,
Expand All @@ -69,7 +71,8 @@ module.exports = async (defaultPort) => {
urls,
useYarn,
webpack,
useTypeScript
useTypeScript,
tscCompileOnError
})
const serverConfig = {
...config.devServer,
Expand All @@ -79,6 +82,7 @@ module.exports = async (defaultPort) => {
const devServer = new WebpackDevServer(serverConfig, compiler)

// Launch WebpackDevServer.
// eslint-disable-next-line consistent-return
devServer.startCallback(() => {
if (isInteractive) {
clearConsole()
Expand Down
62 changes: 17 additions & 45 deletions src/webpack/webpack.config.build.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const safePostCssParser = require('postcss-safe-parser')
const { SourceMapDevToolPlugin } = require('webpack')
const { merge } = require('webpack-merge')
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')
const StyleExtHtmlWebpackPlugin = require('../webpack-plugins/style-ext-html-webpack-plugin')
const { appSrc, appBuild } = require('../variables/paths')
const { PUBLIC_PATH } = require('../variables/variables')
const configFactory = require('./webpack.config')
const { processWebpackConfig } = require('../utils/custom-config')

const isEnvProductionProfile = process.argv.includes('--profile')

module.exports = () =>
processWebpackConfig(
merge(
Expand All @@ -25,29 +25,8 @@ module.exports = () =>
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'css/[name].[contenthash:8].css',
chunkFilename: 'css/[name].[contenthash:8].chunk.css'
}),
new ScriptExtHtmlWebpackPlugin({
inline: [
// https://github.com/webpack-contrib/mini-css-extract-plugin/issues/85
// temporary fix style.js issue
/styles.*\.js$/
],
defaultAttribute: 'defer',
custom: [
{
test: /\.js$/,
attribute: 'onerror',
value:
'window.__ERR_SCRIPTS__ = (window.__ERR_SCRIPTS__ || []).concat(this.src)'
},
{
test: /\.js$/,
attribute: 'crossorigin',
value: 'anonymous'
}
]
filename: 'css/[name].css',
chunkFilename: 'css/[id].css'
}),
new StyleExtHtmlWebpackPlugin(HtmlWebpackPlugin, {
custom: [
Expand Down Expand Up @@ -83,7 +62,7 @@ module.exports = () =>
new TerserPlugin({
terserOptions: {
parse: {
// we want terser to parse ecma 8 code. However, we don't want it
// We want terser to parse ecma 8 code. However, we don't want it
// to apply any minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
Expand All @@ -107,33 +86,21 @@ module.exports = () =>
mangle: {
safari10: true
},
// Added for profiling in devtools
keep_classnames: isEnvProductionProfile,
keep_fnames: isEnvProductionProfile,
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true
}
},
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
// Disabled on WSL (Windows Subsystem for Linux) due to an issue with Terser
// https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
parallel: true,
// Enable file caching
cache: true,
sourceMap: true
}
}),
// This is only used in production mode
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
parser: safePostCssParser,
map: false
}
})
new CssMinimizerPlugin()
],
moduleIds: 'hashed',
chunkIds: 'named',
splitChunks: {
// 避免生成名字过长的 chunk
name: false,
Expand Down Expand Up @@ -161,7 +128,12 @@ module.exports = () =>
}
}
},
runtimeChunk: { name: 'runtime' }
// Keep the runtime chunk separated to enable long term caching
// https://twitter.com/wSokra/status/969679223278505985
// https://github.com/facebook/create-react-app/issues/5358
runtimeChunk: {
name: (entrypoint) => `runtime-${entrypoint.name}`
}
}
}
)
Expand Down
30 changes: 25 additions & 5 deletions src/webpack/webpack.config.dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ const path = require('path')
const webpack = require('webpack')
const { merge } = require('webpack-merge')
const ignoredFiles = require('react-dev-utils/ignoredFiles')
const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware')
const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware')
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin')
const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware')
const errorOverlayMiddleware = require('react-dev-utils/errorOverlayMiddleware')
const { appPublic, appSrc } = require('../variables/paths')
const { PUBLIC_PATH } = require('../variables/variables')
const configFactory = require('./webpack.config')
const { processWebpackConfig } = require('../utils/custom-config')
const paths = require('../variables/paths')

module.exports = () =>
processWebpackConfig(
Expand All @@ -22,13 +26,16 @@ module.exports = () =>
mode: 'development',
devtool: 'cheap-module-source-map',
output: {
path: paths.appBuild,
// Add /* filename */ comments to generated require()s in the output.
pathinfo: true,
filename: '[name].js',
chunkFilename: '[id].chunk.js',
// see https://github.com/webpack/webpack/issues/6642#issuecomment-370222543
globalObject: 'this',
filename: 'static/js/bundle.js',
chunkFilename: 'static/js/[name].chunk.js',
assetModuleFilename: 'static/media/[name].[hash][ext]',
devtoolModuleFilenameTemplate: (info) =>
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')
path.resolve(info.absoluteResourcePath).replace(/\\/g, '/'),
// see https://github.com/webpack/webpack/issues/6642#issuecomment-370222543
globalObject: 'this'
},
devServer: {
client: {
Expand Down Expand Up @@ -79,6 +86,19 @@ module.exports = () =>
},
onBeforeSetupMiddleware(devServer) {
devServer.app.use(evalSourceMapMiddleware(devServer))
// This lets us open files from the runtime error overlay.
devServer.app.use(errorOverlayMiddleware())
},
onAfterSetupMiddleware(devServer) {
// Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match
devServer.app.use(redirectServedPath(PUBLIC_PATH))

// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
devServer.app.use(noopServiceWorkerMiddleware(PUBLIC_PATH))
}
}
}
Expand Down
Loading

0 comments on commit f9a1f2f

Please sign in to comment.