create-react-app eject后的优化加载速度

刚开始怎么改都报错,说不支持less,一怒之下,重新安装了一次create-react-app,然后创建一个新项目,把原来的代码复制进去,利用新版的create-react-app,成功打包!!
如果你的项目eject后无法打包,也可以尝试一下我这个暴力的方法,如果有更好的方法,可以留言给我~谢谢

-------------------------------------------华丽丽的的分割线------------------------------------------

1.查看build文件夹,发现map文件是最大的,先把他干掉

“build”: “cross-env GENERATE_SOURCEMAP=false node scripts/build.js” // 需要安装cross-env插件,并修改package.json
文件夹大小从15.7M减少到3.2M

2.把组件使用cdn加载,如react,axios,react-redux,react-router-dom,echarts(失败了)
改用另一种方式,dllplugin的方式,配置公共的组件组,
创建一个dll.config.js

const path = require("path");
const webpack = require("webpack");

module.exports = {
    entry: {
        // 提取公共模块
        bundle: [
            "react",
            "react-dom",
            "react-router-dom",
            "react-redux",
            "antd",
            "axios",
            "echarts",
            "react-dnd",
            "react-dnd-html5-backend"
        ],
    },
    output: {
        filename: "[name].dll.js",
        path: path.join(__dirname, "../public/dll"),
        libraryTarget: "var",
        library: "_dll_[name]_[hash]"
    },
    plugins: [
        new webpack.DllPlugin({
            path: path.join(__dirname, "../public/dll", "[name].manifest.json"),
            name: "_dll_[name]_[hash]"
        })
    ]
};

把所有希望公共打包的包名都写在数组里,然后通过 执行 webpack --config config/webpack.dll.config.js --mode production 来制作公共资源包,之后手动放到oss上,
并将路径写在public文件夹下的index.html末尾,用script标签引入。

<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->

    <script src="http://cdn.xxxx.com/dll/bundle.dll.js"></script>
  </body>

3.不使用react-app-rewired build改为使用node ./scripts/build.js
配置如下:
react-app-rewired 配置依赖于config-overrides.js,如果直接改为node ./scripts/builds.js则会报错,找不到antd,样式什么的都会出错,所以要改配置,
把config-overrides.js的配置都一出来

// 之前的config-overrides.js
const {
    override,
    fixBabelImports,
    addLessLoader
} = require('customize-cra');

module.exports = override(
    fixBabelImports('import', {
        libraryName: 'antd',
        libraryDirectory: 'es',
        style: true,
    }),
    addLessLoader({
        javascriptEnabled: true,
        modifyVars: {
            '@primary-color': '#1890ff',
            '@error-color': '#f5222d',
            '@success-color': '#a0d911',
            '@warn-color': '#faad14'
        },
    })
);

首先第一波,babelImports,正常情况下需要创建一个.babelrc,然后在plugins里写下

plugins: ['import', {
     libraryName: 'antd',
     libraryDirectory: 'es',
     style: true,
}]

但是有问题,会报错,说配置文件过多,package.json和.babelrc冲突了,故,删除.babelrc,在package.json中找到babel的配置,并加上设置,改为

"babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
      [
        "import",
        {
          "libraryName": "antd",
          "libraryDirectory": "es",
          "style": true
        }
      ]
    ]
},

之后将下面的lessloader移入webpack.config.js,中对于lessLoader的配置
这里的配置也很简单,

// webpack.config.js中有关于sass的配置项,最简单的方法就是把关于sass的全都复制一遍,然后把sass改为less
// style files regexes
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;

// 下面还有这个 在module下的rules里
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
	test: sassRegex,
	exclude: sassModuleRegex,
	use: getStyleLoaders(
		{
			importLoaders: 3,
			sourceMap: isEnvProduction && shouldUseSourceMap
		},
		"sass-loader"
	),
	// Don't consider CSS imports dead code even if the
	// containing package claims to have no side effects.
	// Remove this when webpack adds a warning or an error for this.
	// See https://github.com/webpack/webpack/issues/6571
	sideEffects: true
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
	test: sassModuleRegex,
	use: getStyleLoaders(
		{
			importLoaders: 3,
			sourceMap: isEnvProduction && shouldUseSourceMap,
			modules: {
				getLocalIdent: getCSSModuleLocalIdent
			}
		},
		"sass-loader"
	)
},

修改后如下

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;

// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
	test: lessRegex,
	exclude: lessModuleRegex,
	use: getStyleLoaders(
		{
			importLoaders: 3,
			sourceMap: isEnvProduction && shouldUseSourceMap
		},
		"less-loader"
	),
	// Don't consider CSS imports dead code even if the
	// containing package claims to have no side effects.
	// Remove this when webpack adds a warning or an error for this.
	// See https://github.com/webpack/webpack/issues/6571
	sideEffects: true
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
	test: lessModuleRegex,
	use: getStyleLoaders(
		{
			importLoaders: 3,
			sourceMap: isEnvProduction && shouldUseSourceMap,
			modules: {
				getLocalIdent: getCSSModuleLocalIdent
			}
		},
		"less-loader"
	)
},

// 然后找到getStyleLoaders方法,修改一下
if (preProcessor) {
	loaders.push({
		loader: require.resolve("resolve-url-loader"),
		options: {
			sourceMap: isEnvProduction && shouldUseSourceMap
		}
	});
	if (preProcessor === "less-loader") {
	
	//  重点配置在这  ///
	
		loaders.push({
			loader: require.resolve(preProcessor),
			options: {
				javascriptEnabled: true,
				modifyVars: {
					"@primary-color": "#1890ff",
					"@error-color": "#f5222d",
					"@success-color": "#a0d911",
					"@warn-color": "#faad14"
				},
				sourceMap: true
			}
		});
	} else {
		loaders.push({
			loader: require.resolve(preProcessor),
			options: {
				sourceMap: true
			}
		});
	}
}

配置后 就可以打包成功了!

优化前优化后
由图可见,主要功劳还是在cdn的使用,让下载速度得到了极大的提升,减少了1s以上,虽然包体大了,但是如果后续网页有新版上线,但是公共资源包是不变的,也就是页面只需要加载1.5M的东西就好了,这样更新之后的加载速度会更快。
使用dll后,再次打包速度会快很多,之前打包要60-80s,现在只要20s不到。

还有很多的优化空间,其他工作任务来了,暂时先这么搞吧,还有路由懒加载等等,如果你们有其他的建议记得给我留言哦,感谢!!希望共同进步!

参考文献:
webpack官网对于dllplugin的介绍
参考的别人的使用方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值