create-react-app同时对多个框架(antd+antd-mobile)做按需加载的方法

18次阅读

共计 1779 个字符,预计需要花费 5 分钟才能阅读完成。

在 React 项目开发中,经常需要引用一些实用的第三方框架。在使用一些比较庞大的第三方框架时,框架内的各种资源文件数量巨大,这时,如果我们在每次使用框架时,都将框架内所有资源都全部加载的话,这将使得页面的性能大大降低。这时,我们就需要对这些庞大的第三方框架做按需加载了。
首先介绍下对单个框架做按需加载的方法
其实在使用 create-react-app 脚手架的情况下,对单个框架做按需加载的方法,网上的相关文章已经很多了,我这里只简单的介绍下。常用的方法就是通过 babel-plugin-import 来实现按需加载,并通过 react-app-rewired 来重写项目配置文件,将 babel-plugin-import 写入配置。
1、安装
cnpm install babel-plugin-import –dev

cnpm install react-app-rewired –dev
2、修改 package.json
“scripts”: {
– “start”: “react-scripts start”,
+ “start”: “react-app-rewired start”,
– “build”: “react-scripts build”,
+ “build”: “react-app-rewired build”,
– “test”: “react-scripts test”,
+ “test”: “react-app-rewired test”,
}
3、在项目的根目录下创建一个 config-overrides.js 用于修改默认配置
const {injectBabelPlugin} = require(‘react-app-rewired’);
const rewireLess = require(‘react-app-rewire-less’);
const path = require(‘path’)

module.exports = function override(config, env) {
config = injectBabelPlugin(
[‘import’,
{
libraryName: ‘antd’,
libraryDirectory: ‘es’,
style: true
}
],
config
);

config = rewireLess.withLoaderOptions({
modifyVars: {“@primary-color”: “#4197FC”},
javascriptEnabled: true,
})(config, env);

return config;
};
这样就完成了对 antd 的按需加载
那么对多个框架做按需加载应该怎么做呢?
对多个框架做按需加载的方法
这里拿 antd 和 antd-mobile 两个框架来举例子
首先还是要按照上面的步骤安装 babel-plugin-import 和 react-app-rewired,并修改默认配置,区别只是在最后一步上。在调用 babel-plugin-import 的 injectBabelPlugin 方法时,需要调用两次,并注明相对应的框架名。具体代码如下:
const {injectBabelPlugin} = require(‘react-app-rewired’);
const rewireLess = require(‘react-app-rewire-less’);
const path = require(‘path’)

module.exports = function override(config, env) {

config = injectBabelPlugin(
[‘import’,
{
libraryName: ‘antd’,
libraryDirectory: ‘es’,
style: true
}, ‘ant’
],
config
);

config = injectBabelPlugin(
[‘import’,
{
libraryName: “antd-mobile”,
libraryDirectory: ‘lib’,
style: true
}, ‘ant-mobile’
],
config
);

config = rewireLess.withLoaderOptions({
modifyVars: {“@primary-color”: “#4197FC”},
javascriptEnabled: true,
})(config, env);

return config;
};

正文完
 0