antd + react model自定义footer_更骚的create-react-app开发环境配置craco
背景
使用 CRA 腳手架創(chuàng)建的項(xiàng)目,如果想要修改編譯配置,通常可能會(huì)選擇 npm run eject 彈出配置后魔改。但是,eject 是不可逆操作,彈出配置后,你將無法跟隨官方的腳步去升級(jí)項(xiàng)目的 react-script 版本。
如果想要無 eject 重寫 CRA 配置,目前成熟的是下面這幾種方式
第二種方式相對(duì)第三種略復(fù)雜一些,我自己很有體會(huì)并且我們注意到最新的AntDesign4 官方也開始推薦 craco 了,那我們還等什么還不快行動(dòng)起來,今天主要在這里詳細(xì)討論一下 craco 的使用,也方便大家給出更好的建議。
配置步驟
3、修改 package.json 中的 scripts
{"scripts":{"start": "set PORT=5000 && craco start FAST_REFRESH=true","build": "set GENERATE_SOURCEMAP=false && craco build","analyzer": "env NODE_ENV=production BUILD_ANALYZER=true yarn start","test": "craco test"} }4、項(xiàng)目根目錄創(chuàng)建 craco.config.js 文件
/* craco.config.js */module.exports = {... }上面用到了幾個(gè)環(huán)境變量: PORT 啟動(dòng)端口 GENERATE_SOURCEMAP 打包時(shí)是否生成 sourceMap BUILD_ANALYZER 文件方式輸出編譯分析
基礎(chǔ)的配置到此完成了,接下來是處理各種配置的覆蓋,完整的 craco.config.js 配置文件結(jié)構(gòu),可以在 craco 官方的文檔中詳細(xì)查詢:Configuration Overview 。擴(kuò)展 babel 配置
雖然可以在 configure 中定義 babel 配置,但 craco 也提供了快捷的方式單獨(dú)去書寫,添加 @babel/preset-env 配置示例如下:/* craco.config.js */module.exports = {babel: {presets: [['@babel/preset-env',{modules: false, // 對(duì)ES6的模塊文件不做轉(zhuǎn)化,以便使用tree shaking、sideEffects等useBuiltIns: 'entry', // browserslist環(huán)境不支持的所有墊片都導(dǎo)入// https://babeljs.io/docs/en/babel-preset-env#usebuiltins// https://github.com/zloirock/core-js/blob/master/docs/2019-03-19-core-js-3-babel-and-a-look-into-the-future.mdcorejs: {version: 3, // 使用core-js@3proposals: true,},},],],plugins: [// 配置 babel-plugin-import['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }, 'antd'],// 配置解析器["@babel/plugin-proposal-decorators", { "legacy": true }],["@babel/plugin-proposal-class-properties", { "loose": true }],["babel-plugin-styled-components", { "displayName": true }]],loaderOptions: {},loaderOptions: (babelLoaderOptions, { env, paths }) => { return babelLoaderOptions; }}, }檢測模塊編譯情況
new WebpackBar({ profile: true }), new CircularDependencyPlugin({exclude: /node_modules/,include: /src/,failOnError: true,allowAsyncCycles: false,cwd: process.cwd() })觀察打包進(jìn)度
const SimpleProgressWebpackPlugin = require('simple-progress-webpack-plugin') module export = {webpack: {plugins: [// 查看打包的進(jìn)度new SimpleProgressWebpackPlugin()]} }修改打包輸出目錄
module.exports = {webpack: {configure: (webpackConfig, {env, paths}) => {// paths.appPath='public'paths.appBuild = 'dist'webpackConfig.output = {...webpackConfig.output,// ...{// filename: whenDev(() => 'static/js/bundle.js', 'static/js/[name].js'),// chunkFilename: 'static/js/[name].js'// },path: path.resolve(__dirname, 'dist'), // 修改輸出文件目錄publicPath: '/'}return webpackConfig}} }如果覺得繁瑣也可以直接使用webpack進(jìn)行configure覆蓋、webpackConfig的信息大概有這么多:
熱更新Hot-loader擴(kuò)展
啟動(dòng)熱更新如何避免頻繁刷新 常用的熱更新方案 react-hot-loader、craco也幫我們提供了兩種craco-plugin-react-hot-reload、craco-fast-refreshreact-hot-loader配置如下(傳送門)
step1:webpack.config.js中引入別名配置解除相關(guān)警告 yarn add @hot-loader/react-dom module.exports = {// ...resolve: {alias: {'react-dom': '@hot-loader/react-dom',},}, }; step2:注入引用App.js import { hot } from 'react-hot-loader/root' function App {return (<div>ceshi</div>) } export default hot(App)craco-plugin-react-hot-reload配置如下(傳送門)
/* craco.config.js */ const reactHotReloadPlugin = require('craco-plugin-react-hot-reload') const reactHotReloadPlugin = require('craco-plugin-react-hot-reload') module.exports = {plugins: [{plugin: reactHotReloadPlugin}] }craco-fast-refresh 配置如下(傳送門)
這是最近發(fā)現(xiàn)的新 craco plugin,相對(duì)于 react-hot-loader好用得多,零配置,不需要修改項(xiàng)目代碼,據(jù)說性能也更好。step1:增加插件 /* craco.config.js */ const FastRefreshCracoPlugin = require('craco-fast-refresh') module.exports = () => {return {plugins: [{plugin: FastRefreshCracoPlugin}],}; }; step2: 注入引用App.js import React from 'react' import { hot } from 'react-hot-loader' const App = () => <div>Hello World!</div>export default hot(module)(App)Antd自定義主題配置
配置antd主題顏色可隨意對(duì)以下方案就行選取結(jié)合lessOptions
step1:運(yùn)行 yarn add craco-less step2:引入 const CracoLessPlugin = require('craco-less') step3:配置 {plugin: CracoLessPlugin,options: {lessLoaderOptions: {lessOptions: {modifyVars: {'@primary-color': '#1DA57A'},javascriptEnabled: true}}} }同時(shí)craco 也提供了專門的 plugin 來處理 antd 的集成(傳送門)配置方式有區(qū)別
Craco自定義支持
craco-antd includes: - Less (provided by craco-less) - babel-plugin-import to only import the required CSS, instead of everything - An easy way to customize the theme. Set your custom variables in ./antd.customize.lessstep1: yarn add craco-antd step2: const CracoAntDesignPlugin = require('craco-antd') step3 {plugin: CracoAntDesignPlugin,options: {customizeTheme: {'@primary-color': '#FF061C'}} }針對(duì)customizeTheme 如果想單獨(dú)抽離可采取如下方案
step1: 新建antd.customize.less文件 --------- @primary-color: #FF061C; --------- step2:讀取模式 {plugin: CracoAntDesignPlugin,options: {customizeThemeLessPath: path.join(__dirname,"antd.customize.less")}}相對(duì)來講使用會(huì)更簡潔一些,推薦使用。
總結(jié)
確實(shí)能夠在不 eject 彈出配置的情況下,能夠自定義所有的 cra 構(gòu)建配置,之前進(jìn)行了詳細(xì)的說明,有這方面的需求可以去看看(傳送門)。因此在后續(xù)的編碼中,我們可以隨便使用這兩種方式構(gòu)建自己的webpack配置。 注意:_configure配置和_craco配置會(huì)互斥謹(jǐn)慎使用
以下,是我整理完整的 craco.config.js 配置,相應(yīng)的demo方便參照 craco 還提供一些其他 plugin具體根據(jù)實(shí)際情況自行加入(傳送門)/* craco.config.js */ /*** TODO: 區(qū)分環(huán)境 —— NODE_ENV* - whenDev ? process.env.NODE_ENV === 'development'* - whenTest ? process.env.NODE_ENV === 'test'* - whenProd ? process.env.NODE_ENV === 'production'*/ const {when, whenDev, whenProd, whenTest, ESLINT_MODES, POSTCSS_MODES } = require('@craco/craco') const webpack = require('webpack') const CracoLessPlugin = require('craco-less') const CracoAntDesignPlugin = require('craco-antd') const CracoVtkPlugin = require('craco-vtk') const WebpackBar = require('webpackbar') const CircularDependencyPlugin = require('circular-dependency-plugin') const FastRefreshCracoPlugin = require('craco-fast-refresh') const TerserPlugin = require('terser-webpack-plugin') const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin') const {BundleAnalyzerPlugin } = require('webpack-bundle-analyzer') const CompressionWebpackPlugin = require('compression-webpack-plugin') const DashboardPlugin = require('webpack-dashboard/plugin') const SimpleProgressWebpackPlugin = require('simple-progress-webpack-plugin')const path = require('path')// 判斷編譯環(huán)境是否為生產(chǎn) const isBuildAnalyzer = process.env.BUILD_ANALYZER === 'true'const pathResolve = pathUrl => path.join(__dirname, pathUrl)module.exports = {webpack: {// 別名配置alias: {'@': pathResolve('.'),src: pathResolve('src'),assets: pathResolve('src/assets'),common: pathResolve('src/common'),components: pathResolve('src/components'),hooks: pathResolve('src/hooks'),pages: pathResolve('src/pages'),store: pathResolve('src/store'),utils: pathResolve('src/utils')// 此處是一個(gè)示例,實(shí)際可根據(jù)各自需求配置},plugins: [// webpack構(gòu)建進(jìn)度條new WebpackBar({profile: true}),new webpack.IgnorePlugin(/^./locale$/, /moment$/),// 查看打包的進(jìn)度new SimpleProgressWebpackPlugin(),// 時(shí)間轉(zhuǎn)換工具采取day替換momentnew AntdDayjsWebpackPlugin(),// // 新增模塊循環(huán)依賴檢測插件...whenDev(() => [new CircularDependencyPlugin({exclude: /node_modules/,include: /src/,failOnError: true,allowAsyncCycles: false,cwd: process.cwd()}),// webpack-dev-server 強(qiáng)化插件new DashboardPlugin(),new webpack.HotModuleReplacementPlugin()], []),/*** 編譯產(chǎn)物分析* - https://www.npmjs.com/package/webpack-bundle-analyzer* 新增打包產(chǎn)物分析插件*/...when(isBuildAnalyzer, () => [new BundleAnalyzerPlugin({analyzerMode: 'static', // html 文件方式輸出編譯分析openAnalyzer: false,reportFilename: path.resolve(__dirname, `analyzer/index.html`)})], []),...whenProd(() => [// new TerserPlugin({// // sourceMap: true, // Must be set to true if using source-maps in production// terserOptions: {// ecma: undefined,// parse: {},// compress: {// warnings: false,// drop_console: true, // 生產(chǎn)環(huán)境下移除控制臺(tái)所有的內(nèi)容// drop_debugger: true, // 移除斷點(diǎn)// pure_funcs: ['console.log'] // 生產(chǎn)環(huán)境下移除console// }// }// }),// 打壓縮包new CompressionWebpackPlugin({algorithm: 'gzip',test: new RegExp('.(' + ['js', 'css'].join('|') + ')$'),threshold: 1024,minRatio: 0.8})], [])],//抽離公用模塊optimization: {splitChunks: {cacheGroups: {commons: {chunks: 'initial',minChunks: 2,maxInitialRequests: 5,minSize: 0},vendor: {test: /node_modules/,chunks: 'initial',name: 'vendor',priority: 10,enforce: true}}}},/*** 重寫 webpack 任意配置* - configure 能夠重寫 webpack 相關(guān)的所有配置,但是,仍然推薦你優(yōu)先閱讀 craco 提供的快捷配置,把解決不了的配置放到 configure 里解決;* - 這里選擇配置為函數(shù),與直接定義 configure 對(duì)象方式互斥;*/configure: (webpackConfig, {env, paths}) => {// paths.appPath='public'paths.appBuild = 'dist' // 配合輸出打包修改文件目錄// webpackConfig中可以解構(gòu)出你想要的參數(shù)比如mode、devtool、entry等等,更多信息請(qǐng)查看webpackConfig.json文件/*** 修改 output*/webpackConfig.output = {...webpackConfig.output,// ...{// filename: whenDev(() => 'static/js/bundle.js', 'static/js/[name].js'),// chunkFilename: 'static/js/[name].js'// },path: path.resolve(__dirname, 'dist'), // 修改輸出文件目錄publicPath: '/'}/*** webpack split chunks*/// webpackConfig.optimization.splitChunks = {// ...webpackConfig.optimization.splitChunks,// ...{// chunks: 'all',// name: true// }// }// 返回重寫后的新配置return webpackConfig}},babel: {presets: [],plugins: [// AntDesign 按需加載['import', {libraryName: 'antd',libraryDirectory: 'es',style: true}, 'antd'],['@babel/plugin-proposal-decorators', {legacy: true}] // 用來支持裝飾器],loaderOptions: {},loaderOptions: (babelLoaderOptions, {env, paths}) => {return babelLoaderOptions}},/*** 新增 craco 提供的 plugin*/plugins: [// 熱更新...whenDev(() => [{plugin: FastRefreshCracoPlugin}, {plugin: CracoVtkPlugin()}, {plugin: new AntdDayjsWebpackPlugin()}], []),// 方案1、配置Antd主題less// {// plugin: CracoLessPlugin,// options: {// lessLoaderOptions: {// lessOptions: {// modifyVars: { '@primary-color': '#1DA57A' },// javascriptEnabled: true// }// }// }// },// 方案2、配置Antd主題// {// plugin: CracoAntDesignPlugin,// options: {// customizeTheme: {// '@primary-color': '#FF061C'// }// }// },// 方案3、配置Antd主題{plugin: CracoAntDesignPlugin,options: {customizeThemeLessPath: path.join(__dirname,"antd.customize.less"),},},],devServer: {port: 9000,proxy: {'/api': {target: 'https://placeholder.com/',changeOrigin: true,secure: false,xfwd: false,}}} }同時(shí)我們也可以看一下官方給我們暴露了哪些Api
const { when, whenDev, whenProd, 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: {}}] };這么多的信息使用起來是不是很爽,想探索的趕快行動(dòng)起來共同進(jìn)步啦
參考
- craco 配置
- less-loader 官方文檔
- ant design 官方文檔
- craco實(shí)踐
總結(jié)
以上是生活随笔為你收集整理的antd + react model自定义footer_更骚的create-react-app开发环境配置craco的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 惠普搜客户机t5740升级硬盘_惠普暗影
- 下一篇: vscode卸载background插件