日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

antd + react model自定义footer_更骚的create-react-app开发环境配置craco

發布時間:2025/3/20 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 antd + react model自定义footer_更骚的create-react-app开发环境配置craco 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

背景

使用 CRA 腳手架創建的項目,如果想要修改編譯配置,通常可能會選擇 npm run eject 彈出配置后魔改。但是,eject 是不可逆操作,彈出配置后,你將無法跟隨官方的腳步去升級項目的 react-script 版本。

如果想要無 eject 重寫 CRA 配置,目前成熟的是下面這幾種方式

  • 通過 CRA 官方支持的 --scripts-version 參數,創建項目時使用自己重寫過的 react-scripts 包
  • 使用 react-app-rewired + customize-cra 組合覆蓋配置
  • 使用 craco 覆蓋配置
  • 第二種方式相對第三種略復雜一些,我自己很有體會并且我們注意到最新的AntDesign4 官方也開始推薦 craco 了,那我們還等什么還不快行動起來,今天主要在這里詳細討論一下 craco 的使用,也方便大家給出更好的建議。

    配置步驟

  • 首先,使用 create-react-app 創建一個項目,這里我們命名為 my-project
  • npx create-react-app my-project
  • 進入項目目錄,安裝基本依賴
  • yarn add antd @craco/craco craco-less @babel/plugin-proposal-decorators babel-plugin-import -D

    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、項目根目錄創建 craco.config.js 文件

    /* craco.config.js */module.exports = {... }

    上面用到了幾個環境變量: PORT 啟動端口 GENERATE_SOURCEMAP 打包時是否生成 sourceMap BUILD_ANALYZER 文件方式輸出編譯分析

    基礎的配置到此完成了,接下來是處理各種配置的覆蓋,完整的 craco.config.js 配置文件結構,可以在 craco 官方的文檔中詳細查詢:Configuration Overview 。

    擴展 babel 配置

    雖然可以在 configure 中定義 babel 配置,但 craco 也提供了快捷的方式單獨去書寫,添加 @babel/preset-env 配置示例如下:/* craco.config.js */module.exports = {babel: {presets: [['@babel/preset-env',{modules: false, // 對ES6的模塊文件不做轉化,以便使用tree shaking、sideEffects等useBuiltIns: 'entry', // browserslist環境不支持的所有墊片都導入// 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() })

    觀察打包進度

    const SimpleProgressWebpackPlugin = require('simple-progress-webpack-plugin') module export = {webpack: {plugins: [// 查看打包的進度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進行configure覆蓋、webpackConfig的信息大概有這么多:

    熱更新Hot-loader擴展

    啟動熱更新如何避免頻繁刷新 常用的熱更新方案 react-hot-loader、craco也幫我們提供了兩種craco-plugin-react-hot-reload、craco-fast-refresh

    react-hot-loader配置如下(傳送門)

    step1:webpack.config.js中引入別名配置解除相關警告 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 配置如下(傳送門)

    這是最近發現的新 craco plugin,相對于 react-hot-loader好用得多,零配置,不需要修改項目代碼,據說性能也更好。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主題顏色可隨意對以下方案就行選取

    結合lessOptions

    step1:運行 yarn add craco-less step2:引入 const CracoLessPlugin = require('craco-less') step3:配置 {plugin: CracoLessPlugin,options: {lessLoaderOptions: {lessOptions: {modifyVars: {'@primary-color': '#1DA57A'},javascriptEnabled: true}}} }

    同時craco 也提供了專門的 plugin 來處理 antd 的集成(傳送門)配置方式有區別

    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'}} }

    針對customizeTheme 如果想單獨抽離可采取如下方案

    step1: 新建antd.customize.less文件 --------- @primary-color: #FF061C; --------- step2:讀取模式 {plugin: CracoAntDesignPlugin,options: {customizeThemeLessPath: path.join(__dirname,"antd.customize.less")}}

    相對來講使用會更簡潔一些,推薦使用。

    總結

    確實能夠在不 eject 彈出配置的情況下,能夠自定義所有的 cra 構建配置,之前進行了詳細的說明,有這方面的需求可以去看看(傳送門)。因此在后續的編碼中,我們可以隨便使用這兩種方式構建自己的webpack配置。 注意:_configure配置和_craco配置會互斥謹慎使用

    以下,是我整理完整的 craco.config.js 配置,相應的demo方便參照 craco 還提供一些其他 plugin具體根據實際情況自行加入(傳送門)/* craco.config.js */ /*** TODO: 區分環境 —— 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')// 判斷編譯環境是否為生產 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')// 此處是一個示例,實際可根據各自需求配置},plugins: [// webpack構建進度條new WebpackBar({profile: true}),new webpack.IgnorePlugin(/^./locale$/, /moment$/),// 查看打包的進度new SimpleProgressWebpackPlugin(),// 時間轉換工具采取day替換momentnew AntdDayjsWebpackPlugin(),// // 新增模塊循環依賴檢測插件...whenDev(() => [new CircularDependencyPlugin({exclude: /node_modules/,include: /src/,failOnError: true,allowAsyncCycles: false,cwd: process.cwd()}),// webpack-dev-server 強化插件new DashboardPlugin(),new webpack.HotModuleReplacementPlugin()], []),/*** 編譯產物分析* - https://www.npmjs.com/package/webpack-bundle-analyzer* 新增打包產物分析插件*/...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, // 生產環境下移除控制臺所有的內容// drop_debugger: true, // 移除斷點// pure_funcs: ['console.log'] // 生產環境下移除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 相關的所有配置,但是,仍然推薦你優先閱讀 craco 提供的快捷配置,把解決不了的配置放到 configure 里解決;* - 這里選擇配置為函數,與直接定義 configure 對象方式互斥;*/configure: (webpackConfig, {env, paths}) => {// paths.appPath='public'paths.appBuild = 'dist' // 配合輸出打包修改文件目錄// webpackConfig中可以解構出你想要的參數比如mode、devtool、entry等等,更多信息請查看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,}}} }

    同時我們也可以看一下官方給我們暴露了哪些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: {}}] };

    這么多的信息使用起來是不是很爽,想探索的趕快行動起來共同進步啦

    參考

    • craco 配置
    • less-loader 官方文檔
    • ant design 官方文檔
    • craco實踐

    總結

    以上是生活随笔為你收集整理的antd + react model自定义footer_更骚的create-react-app开发环境配置craco的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。