React腳手架config-overrides.js文件的配置方式
React腳手架config-overrides.js文件配置
主要講講在react腳手架在不使用eject命令的情況下,如何進行webpack的配置。
網上查詢了好多,只有針對相關的配置,這次全面的看一看配置。
還是一樣,我們需要插件的幫助:
npm install react-app-rewired customize-cra --save-dev
配置package.json:
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test --env=jsdom", "eject": "react-scripts eject" }
在根目錄下創(chuàng)建文件config-overrides.js,這里主要是由插件customize-cra來實現,配置包含兩部分,customizer和utilities
const { override, addTslintLoader,addExternalBabelPlugins,addBabelPlugins,addBabelPresets,babelInclude,babelExclude,removeInternalBabelPlugin,fixBabelImports,addDecoratorsLegacy,disableEsLint,useEslintRc,enableEslintTypescript,addWebpackAlias,addWebpackResolve,addWebpackPlugin,addWebpackExternals,addWebpackModuleRule,setWebpackTarget,setWebpackStats,addBundleVisualizer,addBundleVisualizer,adjustWorkbox,useBabelRc,adjustWorkbox,addLessLoader,addPostcssPlugins,disableChunk} = require("customize-cra"); const path = require("path"); module.exports = override( //customizers //addTslintLoader(loaderOptions),需要安裝tslint-loader addTslintLoader(), //addExternalBabelPlugins(plugins)/addExternalBabelPlugin(plugin),create-reat-app有2種方式配置babel-loader,一種是默認配置,另外一種通過external loader配置,在這里可以使用addExternalBabelPlugin添加插件,同樣你可以使用addBabelPlugin,作用是一樣的。注意如果添加多個插件要使用拓展符。 ...addExternalBabelPlugins( "babel-plugin-transform-do-expressions", "@babel/plugin-proposal-object-rest-spread" ), //addBabelPlugin(plugin)/addBabelPlugins(plugins) ...addBabelPlugins( "polished", "emotion", "babel-plugin-transform-do-expressions" ), //addBabelPreset(preset)/addBabelPresets(...presets)添加babel preset配置,用法如下,與上述的addExternalBabelPlugins寫法相同 ...addBabelPresets( [ "@babel/env", { targets: { browsers: ["> 1%", "last 2 versions"] }, modules: "commonjs" } ], "@babel/preset-flow", "@babel/preset-react" ), //babelInclude(exclude)重寫babel-loader的exclude配置 babelInclude([ path.resolve("src"), // make sure you link your own source path.resolve("node_modules/native-base-shoutem-theme"), path.resolve("node_modules/react-navigation"), path.resolve("node_modules/react-native-easy-grid") ]), //babelExclude(exclude)重寫babel-loader的exclude配置 babelExclude([path.resolve("src/excluded-folder")]), //removeInternalBabelPlugin(pluginName)從配置中移除構造函數名稱與pluginname匹配的特定babel插件 removeInternalBabelPlugin("plugin-name"), //fixBabelImports(libraryName, options),添加 babel-plugin-import 插件,主要用于按需引入 fixBabelImports("lodash", { libraryDirectory: "", camel2DashComponentName: false }), fixBabelImports("react-feather", { libraryName: "react-feather", libraryDirectory: "dist/icons" }), //addDecoratorsLegacy()開啟修飾符,先安裝@babel/plugin-proposal-decorators插件 addDecoratorsLegacy(), //disableEsLint()您可能需要將它與addDecoratorsLegacy一起使用,以便讓裝飾器和導出一起解析。如果你想在EsLint中使用@babel/plugin-proposal-decorators,你可以啟用useEslintRc,如下所述,在你的.eslintrc或package.json中eslintonfig下進行以下配置: //"parserOptions": { // "ecmaFeatures": { // "legacyDecorators": true // } // } disableEsLint(), //useEslintRc(configFile)configFile是一個可選參數,允許指定ESLint配置文件的確切路徑。配置eslint的規(guī)范 useEslintRc(configFile), //enableEslintTypescript()更新Webpack eslint-loader來檢測.js(x)和.ts(x)文件,并在控制臺上顯示檢測錯誤/警告。 enableEslintTypescript(), //addWebpackAlias(alias)將提供的別名信息添加到webpack的別名部分。傳遞一個帶有任意數量條目的對象文字,整個對象將被合并。 addWebpackAlias({ '@': path.resolve('./src') }), //addWebpackResolve(resolve)導入文件的時候可以不用添加文件的后綴名 addWebpackResolve({ extensions: ['.tsx', '.ts', '.js', '.jsx', '.json'], }), //addWebpackPlugin(plugin)添加webpack插件,會被合并到plugins數組中 addWebpackPlugin(new MiniCssExtractPlugin()), //addWebpackExternals(deps) 添加外部依賴,在嘗試將庫卸載到CDN時非常有用。addWebpackExternals也可以接受字符串、函數或正則表達式。有關更多信息,請參閱webpack文檔。 addWebpackExternals({ //如直接以cdn引入的 react: "React", "react-dom": "ReactDom" echarts: "window.echarts", // highcharts:"window.highcharts" }), //addWebpackModuleRule(rule)將提供的規(guī)則添加到webpack配置的module.rules數組中 addWebpackModuleRule({test: /\.txt$/, use: 'raw-loader'}), //setWebpackTarget(target)為webpack設置目標配置變量。正如webpack文檔中描述的那樣,這可以是一個字符串或一個函數。如: webpack默認打包的target是瀏覽器模式。因為我做的是一個nwjs項目,所以需要生成node-webkit的包。 setWebpackTarget('node-webkit') //setWebpackStats(stats)設置webpack的stats屬性。這個屬性允許你在產品版本中定制Webpack的錯誤消息行為。正如webpack文檔中描述的那樣,這可以是一個字符串或一個對象。 setWebpackStats('error-only'), //或者如下對象形式 setWebpackStats({ warningsFilter: [ 'filter', /filter/, (warning) => true ] }), //addBundleVisualizer(options, behindFlag = false)將bundle可視化插件添加到webpack配置中。確保安裝了webpack-bundle-analyzer。默認情況下,傳遞給插件的選項是: //{ //"analyzerMode": "static", //"reportFilename": "report.html" //} addBundleVisualizer({}, true), //setWebpackOptimizationSplitChunks(target)設置自定義優(yōu)化。splitChunks配置到你的webpack配置。請謹慎使用此方法,因為webpack默認配置在大多數時候是有效的。默認情況下,create-react-app中的選項是: //{ //"chunks": "all", //"name": false //} addBundleVisualizer({}, true), //useBabelRc()啟用你的.babelrc(或.babelrc.js) useBabelRc(), //adjustWorkbox(fn)調整Workbox配置。傳遞一個函數,該函數將與當前Workbox配置一起調用,其中您可以根據需要更改配置對象。請看下面的示例。 adjustWorkbox(wb => Object.assign(wb, { skipWaiting: true, exclude: (wb.exclude || []).concat("index.html") }), ); //addLessLoader(loaderOptions)添加less-loader, //npm i -D less less-loader addLessLoader({ strictMath: true, noIeCompat: true, modifyVars: { "@primary-color": "#1DA57A", // 例如, 你使用 Ant Design 改變主題色. }, cssLoaderOptions: {}, // .less 文件被使用在 css-loader 選項 cssModules: { localIdentName: "[path][name]__[local]--[hash:base64:5]", }, }), //如果你在CSS模塊中使用TypeScript (npm init react-app my-app——TypeScript),你應該編輯react-app-env.d.ts。 //declare module "*.module.less" { //const classes: { [key: string]: string }; //export default classes; //} //addPostcssPlugins([plugins])添加postCss插件 addPostcssPlugins([require("postcss-px2rem")({ remUnit: 37.5 })]), //disableChunk()防止默認的靜態(tài)分塊,并強制整個構建到一個文件中。 disableChunk(), //removeModuleScopePlugin()這將刪除CRA插件,防止從src目錄外導入模塊,如果你使用不同的目錄,這很有用。一個常見的用例是如果您在monorepo設置中使用CRA,其中您的包在packages/而不是src/下。 removeModuleScopePlugin(), //watchAll()當應用時,CRA將監(jiān)視項目的所有文件,包括node_modules。要使用它,只需應用它并使用yarn start運行開發(fā)服務器——watch-all watchAll(), //adjustStyleLoaders(callback)逐一找到所有樣式加載器和回調 adjustStyleLoaders(({ use: [ , css, postcss, resolve, processor ] }) => { css.options.sourceMap = true; // css-loader postcss.options.sourceMap = true; // postcss-loader // when enable pre-processor, // resolve-url-loader will be enabled too if (resolve) { resolve.options.sourceMap = true; // resolve-url-loader } // pre-processor if (processor && processor.loader.includes('sass-loader')) { processor.options.sourceMap = true; // sass-loader } }) );
customizer整體配置就是這些。
utilities還有兩個公共方法:
getBabelLoader(config, isOutsideOfApp)
從提供的配置返回babel加載器。
Create-react-app定義了兩個Babel配置,一個用于src/目錄下的js文件,另一個用于該目錄外的任何js文件。
這個函數可以使用isOutsideOfApp參數。
tap(options)
通過在控制臺中或單獨的文件中打印配置,使用tap幫助您在某些點上識別配置。
Tap接受一個帶有next屬性的可選選項對象:
message
:配置前要打印的字符串消息dest
:寫日志的目的文件
const { override, tap, addLessLoader } = require("customize-cra"); module.exports = override( // Print initial config in the console prepending a message tap({ message: "Pre - Customizers" }) /* Your customizers: eg. addLessLoader() */ addLessLoader() // Print final config in a separate file tap({ dest: 'customize-cra.log'}) )
補充:
另外一種拋出對象的寫法 ,我們想要訪問webpack里一些特定模塊:
const {override, fixBabelImports, addLessLoader, overrideDevServer, watchAll} = require('customize-cra') const packageName = require('./package.json').name module.exports = { 'webpack': override( (config) => { config.output = config.output || {} config.output.library = `${packageName}-[name]` config.output.libraryTarget = 'umd' config.output.jsonpFunction = `webpackJsonp_${packageName}` return config }, fixBabelImports('import', { libraryName: 'antd', libraryDirectory: 'es', style: true, }), addLessLoader({ javascriptEnabled: true, modifyVars: { 'primary-color': '#1DA57A', 'link-color': '#1DA57A', 'border-radius-base': '2px', }, }) ), 'devServer': overrideDevServer( (config) => { config.headers = config.headers || {} config.headers['Access-Control-Allow-Origin'] = '*' return config }, watchAll() ) }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
React掌握openapi-typescript-codegen快速生成API客戶端代碼的過程
openapi-typescript-codegen是一個開源工具,用于根據OpenAPI規(guī)范自動生成TypeScript代碼,包括類型定義和API客戶端代碼,它幫助開發(fā)者節(jié)省手動編寫代碼的時間,提高開發(fā)效率,感興趣的朋友一起看看吧2024-11-11react-three/postprocessing庫的參數中文含義使用解析
這篇文章主要介紹了react-three/postprocessing庫的參數中文含義使用總結,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-05-05