一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第13天,点击查看活动详情。
1、生产环境优化
根据是否为生产环境对redux中间件进行优化
在store/index.js 中:
let middlewares
if (process.env.NODE_ENV === 'production') {
// 生产环境,只启用 thunk 中间件
middlewares = applyMiddleware(thunk)
} else {
middlewares = composeWithDevTools(applyMiddleware(thunk))
}
2、去掉console
首先下包
npm i terser-webpack-plugin@4.2.3
在craco.config.js中配置
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
webpack: {
// 省略其他...
plugins: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: process.env.NODE_ENV === 'production'
// 生产环境下移除控制台所有的内容
}
}
})
]
}
}
3、配置CDN
1、 打包的时候不打包进来
2、 在public/index.html中引入外部链接
3、通过 craco 来修改 webpack 配置,从而实现 CDN 优化
在craco.config.js 中:
const path = require('path')
// HtmlWebpackPlugin
const { whenProd, getPlugin, pluginByName } = require('@craco/craco')
module.exports = {
webpack: {
alias: {
'@': path.join(__dirname, 'src')
},
configure: (webpackConfig) => {
let cdn = {
js: [],
css: []
}
// 对webpack进行配置
whenProd(() => {
// 只会在生产环境执行
webpackConfig.externals = {
react: 'React',
'react-dom': 'ReactDOM',
redux: 'Redux',
}
cdn = {
js: [
'https://cdn.bootcdn.net/ajax/libs/react/17.0.2/umd/react.production.min.js',
'https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js',
'https://cdn.bootcdn.net/ajax/libs/redux/4.1.0/redux.min.js'
],
css: []
}
})
const { isFound, match } = getPlugin(
webpackConfig,
pluginByName('HtmlWebpackPlugin')
)
if (isFound) {
// 找到了html的插件
match.options.cdn = cdn
}
return webpackConfig
}
}
}
然后在public/index.html 中:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>
<%= webpackConfig.name %>
</title>
<% if(process.env.NODE_ENV==='production' ) { %>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/xlsx.full.min.js"></script>
<% } %>
</head>
<body>
<noscript>
<strong>We're sorry but <%= webpackConfig.name %> doesn't work properly without JavaScript enabled. Please enable it
to continue.</strong>
</noscript>
<div id="app"></div>
</body>
</html>