create-react-app同時對多個框架(antd+antd-mobile)做按需加載的方法

在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-importreact-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;
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章