React projects often use useful third-party frameworks. With some large third-party frameworks, the number of resource files in the framework is huge, and if we load all the resources in the framework every time we use the framework, the performance of the page will be significantly reduced. This is where we need to load these massive third-party frameworks on demand.
Let’s start with the method of loading a single framework on demand
In the case of create-React-app scaffolding, there are a lot of articles on the Internet about how to load a single frame on demand. The usual approach is to load on demand via babel-plugin-import, and rewrite the project configuration file via react-app-rewired to write babel-plugin-import into the configuration.
1, install,
cnpm install babel-plugin-import --dev
cnpm install react-app-rewired --dev
Copy the code
2. Modify 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",}Copy the code
3. Create a config-overrides. Js file in the root directory of the project to modify the default configuration
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;
};
Copy the code
This completes the on-demand loading of ANTD
So what do you do when you load multiple frameworks on demand?
A method of loading multiple frameworks on demand
Take antD and ANTD-Mobile as examples
Install babel-plugin-import and react-app-rewired as shown above, and modify the default configuration. The difference is only in the last step. The injectBabelPlugin method of babel-plugin-import needs to be called twice with the corresponding framework name. The specific code is as follows:
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;
};
Copy the code