react在不彈出eject的情況下配置sass和antd

天氣越來越熱,公司的業務也慢慢放緩,這時候就有空暇時間爲自己充點電了,然後就把目標放在了react上,公司的前端技術框架用的是vue。對react早就如雷貫耳,然後自己看了文檔就劈里啪啦開始搞。在用create-react-app腳手架搭建項目的時候遇到一些配置上的小坑,所以在這裏筆記一下。

配置sass

從react-scripts 2.0.0開始就支持直接配置sass了,安裝個node-sass依賴即可

npm install node-sass --save-dev
複製代碼

這時問題來了,公共sass文件怎麼管理呢?不可能每個頁面都去引入一次吧,這時候想到了webpack來配置,不過create-react-app在不彈出eject時是沒有webpack.config.js文件的。在antd按需加載的文檔裏面發現了一個craco的庫可以解決這個問題,同時也可以很簡單進行其他配置:

npm install @craco/craco --save
複製代碼

依賴下載完成後,修改package.json裏面的scripts:

// package.json
"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  }
複製代碼

在項目根目錄新建一個craco.config.js的文件,你可以進行如下的配置(此處直接貼了一版@craco官方可配置項):

const { when, whenDev, whenProd, whenCI, whenTest, ESLINT_MODES, POSTCSS_MODES } = require("@craco/craco");

module.exports = {
    reactScriptsVersion: "react-scripts" /* (default value) */,
    style: {
        modules: {
            localIdentName: ""
        },
        css: {
            loaderOptions: { /* Any css-loader configuration options: https://github.com/webpack-contrib/css-loader. */ },
            loaderOptions: (cssLoaderOptions, { env, paths }) => { return cssLoaderOptions; }
        },
        sass: {
            loaderOptions: { /* Any sass-loader configuration options: https://github.com/webpack-contrib/sass-loader. */ },
            loaderOptions: (sassLoaderOptions, { env, paths }) => { return sassLoaderOptions; }
        },
        postcss: {
            mode: "extends" /* (default value) */ || "file",
            plugins: [],
            env: {
                autoprefixer: { /* Any autoprefixer options: https://github.com/postcss/autoprefixer#options */ },
                stage: 3, /* Any valid stages: https://cssdb.org/#staging-process. */
                features: { /* Any CSS features: https://preset-env.cssdb.org/features. */ }
            },
            loaderOptions: { /* Any postcss-loader configuration options: https://github.com/postcss/postcss-loader. */ },
            loaderOptions: (postcssLoaderOptions, { env, paths }) => { return postcssLoaderOptions; }
        }
    },
    eslint: {
        enable: true /* (default value) */,
        mode: "extends" /* (default value) */ || "file",
        configure: { /* Any eslint configuration options: https://eslint.org/docs/user-guide/configuring */ },
        configure: (eslintConfig, { env, paths }) => { return eslintConfig; },
        loaderOptions: { /* Any eslint-loader configuration options: https://github.com/webpack-contrib/eslint-loader. */ },
        loaderOptions: (eslintOptions, { env, paths }) => { return eslintOptions; }
    },
    babel: {
        presets: [],
        plugins: [],
        loaderOptions: { /* Any babel-loader configuration options: https://github.com/babel/babel-loader. */ },
        loaderOptions: (babelLoaderOptions, { env, paths }) => { return babelLoaderOptions; }
    },
    typescript: {
        enableTypeChecking: true /* (default value)  */
    },
    webpack: {
        alias: {},
        plugins: [],
        configure: { /* Any webpack configuration options: https://webpack.js.org/configuration */ },
        configure: (webpackConfig, { env, paths }) => { return webpackConfig; }
    },
    jest: {
        babel: {
            addPresets: true, /* (default value) */
            addPlugins: true  /* (default value) */
        },
        configure: { /* Any Jest configuration options: https://jestjs.io/docs/en/configuration. */ },
        configure: (jestConfig, { env, paths, resolve, rootDir }) => { return jestConfig; }
    },
    devServer: { /* Any devServer configuration options: https://webpack.js.org/configuration/dev-server/#devserver. */ },
    devServer: (devServerConfig, { env, paths, proxy, allowedHost }) => { return devServerConfig; },
    plugins: [
        {
            plugin: {
                overrideCracoConfig: ({ cracoConfig, pluginOptions, context: { env, paths } }) => { return cracoConfig; },
                overrideWebpackConfig: ({ webpackConfig, cracoConfig, pluginOptions, context: { env, paths } }) => { return webpackConfig; },
                overrideDevServerConfig: ({ devServerConfig, cracoConfig, pluginOptions, context: { env, paths, proxy, allowedHost } }) => { return devServerConfig; },
                overrideJestConfig: ({ jestConfig, cracoConfig, pluginOptions, context: { env, paths, resolve, rootDir } }) => { return jestConfig };
            },
            options: {}
        }
    ]
};
複製代碼

根據上面的配置項開始配置全局sass文件:

module.exports = {
    // ...
    style: {
        sass: {
            loaderOptions: {
                data: `@import "~@/assets/css/variable.scss";@import "~@/assets/css/base.scss";`
            }
        }
    }
}
複製代碼

以上就將全局sass配置好了。但緊接着問題又來了,想要爲項目引入UI框架怎麼引入?譬如antd。antd官方已經給出了按需加載的現成方法,按照官網步驟即可引入成功,但這裏我們已經引入了@craco庫,又該如何按需加載呢?craco-antd可以結合@craco來解決這個問題:

npm install -save craco-antd
複製代碼

下載完成後在craco.config.js中引入:

const CracoAntDesignPlugin = require("craco-antd")
module.exports = {
    // ...
    plugins: [{ plugin: CracoAntDesignPlugin }]
}
複製代碼

以上完成了對antd的按需引入。你還可以進行本地跨域、別名等常用配置:

devServer、alias配置

const CracoAntDesignPlugin = require("craco-antd")
module.exports = {
    // ...
    webpack: {
        // 別名
        alias: {
            '@': path.resolve('src')
        }
    },
    devServer: {
        port: 9999, // 端口配置
        proxy: {
            '/api': {
                target: 'http://xxx.com',
                ws: false, // websocket
                changeOrigin: true, //是否跨域
                secure: false,  // 如果是https接口,需要配置這個參數
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
}
複製代碼

結語

以上是在學習react時遇到的一些配置問題。若有寫得不對的地方,請多多指教。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章