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

Commit

Permalink
fix: 解决build时一些问题
Browse files Browse the repository at this point in the history
  • Loading branch information
virgoone committed Sep 20, 2021
1 parent 9fceff2 commit 5374005
Show file tree
Hide file tree
Showing 7 changed files with 550 additions and 467 deletions.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,14 @@
"fs-extra": "^10.0.0",
"html-webpack-plugin": "^5.3.2",
"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-normalize": "^10.0.1",
"postcss-preset-env": "^6.7.0",
"react-dev-utils": "^11.0.4",
"postcss-safe-parser": "^6.0.0",
"react-dev-utils": "11.0.4",
"resolve-url-loader": "^4.0.0",
"sass": "^1.41.1",
"sass-loader": "^12.1.0",
Expand Down
2 changes: 1 addition & 1 deletion src/commands/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ process.on('unhandledRejection', (err) => {
const webpack = require('webpack')
const fs = require('fs-extra')
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 { appPath, appBuild, appPublic, appHtml } = require('../variables/paths')
const formatWebpackMessages = require('../dev-utils/formatWebpackMessages')

const { measureFileSizesBeforeBuild, printFileSizesAfterBuild } =
FileSizeReporter
Expand Down
128 changes: 128 additions & 0 deletions src/dev-utils/formatWebpackMessages.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable */
'use strict'

const friendlySyntaxErrorLabel = 'Syntax error:'

function isLikelyASyntaxError(message) {
return message.indexOf(friendlySyntaxErrorLabel) !== -1
}

// Cleans up webpack error messages.
function formatMessage(message) {
let lines = []

if (typeof message === 'string') {
lines = message.split('\n')
} else if ('message' in message) {
lines = message['message'].split('\n')
} else if (Array.isArray(message)) {
message.forEach((message) => {
if ('message' in message) {
lines = message['message'].split('\n')
}
})
}

// Strip webpack-added headers off errors/warnings
// https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
lines = lines.filter((line) => !/Module [A-z ]+\(from/.test(line))

// Transform parsing error into syntax error
// TODO: move this to our ESLint formatter?
lines = lines.map((line) => {
const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(
line
)
if (!parsingError) {
return line
}
const [, errorLine, errorColumn, errorMessage] = parsingError
return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`
})

message = lines.join('\n')
// Smoosh syntax errors (commonly found in CSS)
message = message.replace(
/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g,
`${friendlySyntaxErrorLabel} $3 ($1:$2)\n`
)
// Clean up export errors
message = message.replace(
/^.*export '(.+?)' was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$2'.`
)
message = message.replace(
/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$2' does not contain a default export (imported as '$1').`
)
message = message.replace(
/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$3' (imported as '$2').`
)
lines = message.split('\n')

// Remove leading newline
if (lines.length > 2 && lines[1].trim() === '') {
lines.splice(1, 1)
}
// Clean up file name
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) {
lines = [
lines[0],
lines[1]
.replace('Error: ', '')
.replace('Module not found: Cannot find file:', 'Cannot find file:')
]
}

// Add helpful message for users trying to use Sass for the first time
if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {
lines[1] = 'To import Sass files, you first need to install sass.\n'
lines[1] +=
'Run `npm install sass` or `yarn add sass` inside your workspace.'
}

message = lines.join('\n')
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by webpack. For more information see
// https://github.com/facebook/create-react-app/pull/1050
message = message.replace(
/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
''
) // at ... ...:x:y
message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, '') // at <anonymous>
lines = message.split('\n')

// Remove duplicated newlines
lines = lines.filter(
(line, index, arr) =>
index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()
)

// Reassemble the message
message = lines.join('\n')
return message.trim()
}

function formatWebpackMessages(json) {
const formattedErrors = json.errors.map(formatMessage)
const formattedWarnings = json.warnings.map(formatMessage)
const result = { errors: formattedErrors, warnings: formattedWarnings }
if (result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
result.errors = result.errors.filter(isLikelyASyntaxError)
}
return result
}

module.exports = formatWebpackMessages
36 changes: 26 additions & 10 deletions src/webpack/webpack.config.build.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const TerserPlugin = require('terser-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { SourceMapDevToolPlugin } = require('webpack')
const { merge } = require('webpack-merge')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const safePostCssParser = require('postcss-safe-parser')
const StyleExtHtmlWebpackPlugin = require('../webpack-plugins/style-ext-html-webpack-plugin')
const { appSrc, appBuild } = require('../variables/paths')
const { PUBLIC_PATH } = require('../variables/variables')
Expand All @@ -25,17 +27,30 @@ module.exports = () =>
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: 'css/[name].css',
chunkFilename: 'css/[id].css'
filename: 'css/[name].[contenthash:8].css',
chunkFilename: 'css/[name].[contenthash:8].chunk.css',
attributes: {
onerror: '__STYLE_LOAD_ERROR__(event)'
}
}),
new StyleExtHtmlWebpackPlugin(HtmlWebpackPlugin, {
custom: [
{
test: /\.css$/,
attribute: 'onerror',
value: '__STYLE_LOAD_ERROR__(event)'
}
]
// new StyleExtHtmlWebpackPlugin(HtmlWebpackPlugin, {
// custom: [
// {
// test: /\.css$/,
// attribute: 'onerror',
// value: '__STYLE_LOAD_ERROR__(event)'
// }
// ]
// }),
// This is only used in production mode
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
parser: safePostCssParser,
map: false
},
cssProcessorPluginOptions: {
preset: ['default', { minifyFontValues: { removeQuotes: false } }]
}
})
]
}),
Expand All @@ -53,6 +68,7 @@ module.exports = () =>
path: appBuild,
filename: 'js/[name].[chunkhash:8].js',
chunkFilename: 'js/[name].[chunkhash:8].chunk.js',
assetModuleFilename: 'static/media/[name].[hash][ext]',
devtoolModuleFilenameTemplate: (info) =>
path.relative(appSrc, info.absoluteResourcePath).replace(/\\/g, '/')
},
Expand Down
1 change: 0 additions & 1 deletion src/webpack/webpack.config.dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ module.exports = () =>
pathinfo: true,
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, '/'),
// see https://github.com/webpack/webpack/issues/6642#issuecomment-370222543
Expand Down
Loading

0 comments on commit 5374005

Please sign in to comment.