cra
- const paths = require('react-scripts/config/paths');
- paths.appBuild = path.join(path.dirname(paths.appBuild), 'dist'); // 修改打包目录
- // Override `create-react-app` default configs for Jest.
- const jestConfig = require('./jest.config');
- module.exports = {
- jest(config) {
- return { ...config, ...jestConfig };
- },
- };
- module.exports = function override(config, env) {
- config.module.rules = config.module.rules.map(rule => {
- if (rule.oneOf instanceof Array) {
- return {
- ...rule,
- oneOf: [
- {
- test: /\.(svg|png|jpg|jpeg|gif|bmp|tiff)$/i,
- use: [
- {
- loader: 'file-loader',
- options: {
- name: '[path][name]-[hash:8].[ext]'
- }
- }
- ]
- },
- ...rule.oneOf
- ]
- };
- }
- return rule;
- });
- return config;
- }
Putting react-app-rewired config AFTER customize-cra worked for me. It doesn't work though if I assign an object to config, but works if I fix config line by line. I'm sure there is a more elegant solution.
- module.exports = function override(config, env) {
- const APP = process.env.REACT_APP_APP
- const BRAND = process.env.REACT_APP_BRAND
- addWebpackAlias({
- ['@app-config']: path.resolve(__dirname, `./src/brands/${BRAND}/app`),
- })
- config.entry = `./src/${APP}/index.js`
- config.resolve.alias['@app-config'] = path.resolve(__dirname, `./src/brands/${BRAND}`)
- config.resolve.modules = [
- path.join(__dirname, `src/brands/${BRAND}`)
- ].concat(config.resolve.modules)
- return config
- };
Can i replace options only for specific plugin without reseting all plugins created by react-app?
- const path = require('path');
- const { CleanWebpackPlugin } = require('clean-webpack-plugin');
- const HtmlWebpackPlugin = require('html-webpack-plugin');
- const MiniCssExtractPlugin = require('mini-css-extract-plugin');
- module.exports = function override(config, env) {
- if( !config.plugins ) {
- config.plugins = [];
- }
- const miniCssOptions = {
- filename: "[name].[hash].css"
- }
- let miniCssAdded = false;
- if( config.plugins.length ) {
- config.plugins.forEach( p => {
- if( p instanceof MiniCssExtractPlugin) {
- delete p;
- p = new MiniCssExtractPlugin( miniCssOptions );
- miniCssAdded = true;
- }
- })
- }
- if( !miniCssAdded ) {
- config.plugins.push( new MiniCssExtractPlugin( miniCssOptions ) );
- }
- config.plugins.push( new CleanWebpackPlugin() );
- config.plugins.push( new HtmlWebpackPlugin({
- title: 'Caching',
- }) );
- config.output.filename ='static/js/[name].[hash].js';
- config.output.chunkFilename ='static/js/[name].[hash].js';
- config.output.path = path.resolve(__dirname, 'build');
- config.optimization.splitChunks= {
- cacheGroups: {
- vendor: {
- test: /[\\/]node_modules[\\/]/,
- name: 'vendors',
- chunks: 'all',
- }
- }
- }
- return config;
- }
I think you almost made it. But delete p
is NOT a way to delete item from an array. you should use .splice
, which can delete items from array and add items in the meantime:
- config.plugins.forEach( (p,i) => {
- if( p instanceof MiniCssExtractPlugin) {
- //delete p;
- config.plugins.splice(i,1, new MiniCssExtractPlugin( miniCssOptions ));
- }
- })
- const path = require('path');
- const { CleanWebpackPlugin } = require('clean-webpack-plugin');
- const HtmlWebpackPlugin = require('html-webpack-plugin');
- const MiniCssExtractPlugin = require('mini-css-extract-plugin');
- module.exports = function override(config, env) {
- if( !config.plugins ) {
- config.plugins = [];
- }
- const miniCssOptions = {
- filename: "[name].[hash].css"
- }
- let miniCssAdded = false;
- if( config.plugins.length ) {
- config.plugins.forEach( p => {
- if( p instanceof MiniCssExtractPlugin) {
- delete p;
- p = new MiniCssExtractPlugin( miniCssOptions );
- miniCssAdded = true;
- }
- })
- }
- if( !miniCssAdded ) {
- config.plugins.push( new MiniCssExtractPlugin( miniCssOptions ) );
- }
- config.plugins.push( new CleanWebpackPlugin() );
- config.plugins.push( new HtmlWebpackPlugin({
- title: 'Caching',
- }) );
- config.output.filename ='static/js/[name].[hash].js';
- config.output.chunkFilename ='static/js/[name].[hash].js';
- config.output.path = path.resolve(__dirname, 'build');
- config.optimization.splitChunks= {
- cacheGroups: {
- vendor: {
- test: /[\\/]node_modules[\\/]/,
- name: 'vendors',
- chunks: 'all',
- }
- }
- }
- return config;
- }
- "scripts": {
- "format": "prettier --write",
- "start": "PORT=3001 react-app-rewired start",
- "build": "react-app-rewired build",
- "test": "react-app-rewired test"
- },
You can use
useBabelRc()
function ofcustomize-cra
and in .babelrc, you can write babel config for antd.
- {
- "plugins": ["@babel/plugin-proposal-optional-chaining"]
- }
- https://medium.com/@adostes/enabling-optional-chaining-in-a-create-react-app-a9f626a515d9
- var paths = require('react-scripts-ts/config/paths')
- module.exports = function override(config) {
- config.module.rules.push({
- test: /\.(js|jsx)$/,
- include: paths.appSrc,
- loader: require.resolve('babel-loader'),
- options: {
- babelrc: false,
- presets: [require.resolve('babel-preset-react-app')],
- cacheDirectory: true,
- },
- });
- config.module.rules.push({
- test: /\.(ts|tsx)$/,
- include: paths.appSrc,
- loader: ['ts-loader'],
- });
- return config
- }
Import typescript file inside javascript file
https://mikebridge.github.io/post/getting-started-typescript-react/
How do I change `src` folder to something else in create-react-app
- const path = require('path');
- module.exports = {
- paths: function (paths, env) {
- paths.appIndexJs = path.resolve(__dirname, 'mysrc/client.js');
- paths.appSrc = path.resolve(__dirname, 'mysrc');
- return paths;
- },
- }
https://github.com/timarney/react-app-rewired#extended-configuration-options
- module.exports = override(
- config => ({
- ...config,
- output: {
- ...config.output,
- globalObject: 'this',
- },
- }),
- addWebpackModuleRule({
- test: /\.worker\.js$/,
- use: { loader: 'worker-loader' },
- }),
- // addWebpackModuleRule({
- // test: /\.wasm$/,
- // use: { loader: 'wasm-loader' },
- // }),
//https://github.com/YumcoderCom/yumgram/blob/master/config-overrides.js
- module.exports = {
- webpack (config, env) {
- // Log current env
- console.log('Current env', env)
- // Inject global vars
- config.plugins = (config.plugins || []).concat([new webpack.DefinePlugin({
- ...constants[env], ENV: `'${env}'`
- })])
- config = override(
- // Inject lazy loading for ant design css
- fixBabelImports('import', {
- libraryName: 'antd',
- libraryDirectory: 'es',
- style: true,
- }),
- // And override styles
- addLessLoader({
- javascriptEnabled: true,
- modifyVars: {
- '@primary-color': '#3DBD7D',
- '@link-color': '#5678a4',
- '@success-color': '#3DBD7D',
- '@warning-color': '#ffaa00',
- '@error-color': '#E94A4C',
- '@border-color-base': '#3DBD7D',
- '@box-shadow-base' : 'none'
- }
- }),
- // Inject translation
- ...addBabelPlugins('@lingui/babel-plugin-transform-js', '@lingui/babel-plugin-transform-react')
- )(config, env)
- // Return the webpack config
- return config
- }
- }
- const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
- module.exports = function override(config, env) {
- config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin));
- return config;
- };
按照 npm 包页上的步骤操作(安装包并在包.json 文件中翻转调用),并使用与此类似的文件:config-overrides.js
这将从使用的 WebPack 插件中删除 ModuleScopePlugin,但保留其余内容,并消除弹出的必要性。
- module.exports = config => {
- const scopePluginIndex = config.resolve.plugins.findIndex(
- ({ constructor }) => constructor && constructor.name === "ModuleScopePlugin"
- );
- config.resolve.plugins.splice(scopePluginIndex, 1);
- return config;
- };
- 配置重写.js
- const { removeModuleScopePlugin } = require('customize-cra')
- module.exports = removeModuleScopePlugin()
- 配置重写.js
- const ModuleScopePlugin = require("react-dev-utils/ModuleScopePlugin");
- const path = require("path");
- module.exports = function override(config) {
- config.resolve.plugins.forEach(plugin => {
- if (plugin instanceof ModuleScopePlugin) {
- plugin.allowedFiles.add(path.resolve("./config.json"));
- }
- });
- //https://stackoverflow.com/questions/44114436/the-create-react-app-imports-restriction-outside-of-src-directory/58863926?r=SearchResults#
- return config;
- };
- //Customizing antd Less or Css for create-react-app
- function addLessRule(config, env)
- {
- const { getLoader, loaderNameMatches } = require("react-app-rewired");
- const fileLoader = getLoader(
- config.module.rules,
- rule => loaderNameMatches(rule, 'file-loader')
- );
- const lessExtension = /\.less$/;
- fileLoader.exclude.push(lessExtension);
- const cssRules = getLoader(
- config.module.rules,
- rule => String(rule.test) === String(/\.css$/)
- );
- var lessModifyVars = {
- 'primary-color': '#990000',
- 'link-color': '#1DA57A',
- 'border-radius-base': '2px',
- 'layout-header-background' : '#f0f2f5'
- };
- var lessLoaders = [
- { loader: 'style-loader'} ,
- { loader: 'css-loader' },
- { loader: 'less-loader', options: {
- modifyVars: lessModifyVars
- } }
- ];
- lessRule = {
- test : lessExtension,
- use: lessLoaders,
- }
- config.module["rules"].push( lessRule );
- return config
- }
- //https://stackoverflow.com/questions/44611056/customizing-antd-less-or-css-for-create-react-app/51109561?r=SearchResults#51109561
- //django-webpack-loader not rendering react app using react-app-rewired
- var BundleTracker = require('webpack-bundle-tracker');
- module.exports = {
- webpack: (config, env) => {
- config.plugins.push(
- new BundleTracker({
- path: __dirname,
- filename: './build/webpack-stats.json'
- }),
- );
- return config;
- },
- };
- //https://stackoverflow.com/questions/54241751/django-webpack-loader-not-rendering-react-app-using-react-app-rewired?r=SearchResults
- //How do I debug a local typescript module used by an app created from create-react-app
- /* config-overrides.js */
- const rewireAliases = require("react-app-rewire-aliases");
- const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
- var path = require("path");
- module.exports = function override(config, env) {
- config.module.rules.push({
- test: /\.ts$/,
- use: ["awesome-typescript-loader"],
- enforce: "pre"
- });
- config.resolve.plugins = config.resolve.plugins.filter(plugin => !(plugin instanceof ModuleScopePlugin));
- config = rewireAliases.aliasesOptions({
- "@common": path.resolve(
- __dirname,
- `node_modules/my-common-module/src/index.ts`
- )
- })(config, env);
- return config;
- };
- //https://stackoverflow.com/questions/57605815/how-do-i-debug-a-local-typescript-module-used-by-an-app-created-from-create-reac/57649317?r=SearchResults#57649317
- //Create-react-app + react-app-rewired + typescript + antd
- const {
- getLoader,
- injectBabelPlugin
- } = require("react-app-rewired");
- const tsImportPluginFactory = require('ts-import-plugin')
- module.exports = function override(config, env) {
- // do stuff with the webpack config...
- const tsLoader = getLoader(
- config.module.rules,
- rule =>
- rule.loader &&
- typeof rule.loader === 'string' &&
- rule.loader.includes('ts-loader')
- );
- tsLoader.options = {
- getCustomTransformers: () => ({
- before: [
- tsImportPluginFactory([{
- libraryDirectory: 'es',
- libraryName: 'antd',
- style: 'css',
- }]),
- ]
- })
- };
- return config;
- };
- //https://stackoverflow.com/questions/49698564/create-react-app-react-app-rewired-typescript-antd/50022172?r=SearchResults#50022172
- optimization: {
- runtimeChunk: {
- name: 'manifest'
- },
- splitChunks: {
- maxInitialRequests: 10,
- cacheGroups: {
- vendor: {
- test: /(jquery|fastclick|vue.esm.js)/,
- name: 'vendor',
- chunks: 'all'
- },
- common: {
- test: /(\.(png|jpe?g|gif|svg))/,
- name: 'app',
- chunks: 'initial',
- minChunks: 10
- },
- app: {
- test: /(css[\\/]style.css)/,
- name: 'app',
- chunks: 'initial',
- minChunks: 1
- }
- }
- }
- },
- //你可以配置optimization,把你想要抽取的css,js,甚至是公用图片都抽取出来,例如:
- //https://segmentfault.com/q/1010000017990233/
cra的更多相关文章
- 摄像头模组光学CRA(chief ray angle)
http://blog.csdn.net/sylorchen/article/details/54618874 Lens CRA CRA(Chief Ray Angle):从镜头的传感器一侧,可以聚焦 ...
- camera中LENS和SENSOR的CRA是如何搭配的?
camera中LENS和SENSOR的CRA是如何搭配的? camera中,lens和sensor的搭配是非常关键的问题.但这两者是如何搭配的呢? 一般在Sensor data sheet中会附有全视 ...
- react CRA antd 按需加载配置 lessloader
webpack配置 webpack.config.dev.js, webpack.config.prod同理. 'use strict'; const autoprefixer = require(' ...
- 使用CRA开发的基于React的UI组件发布到内网NPM上去
前言:构建的ES组件使用CNPM发布内网上过程 1. 使用Create-React-APP开的组件 如果直接上传到NPM,你引用的时候会报: You may need an appropriate l ...
- [React] Remove React PropTypes by using Flow Annotations (in CRA)
Starting from v15.5 if we wanted to use React's PropTypes we had to change our code to use a separat ...
- cacert.pem
## ## Bundle of CA Root Certificates ## ## Certificate data from Mozilla as of: Wed Sep 14 03:12:05 ...
- java web学习总结(七) -------------------HttpServletResponse对象(一)
Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象.和代表响应的response对象.request和response对象即然代表请求和响应,那我们要 ...
- STM32F105解密STM32F105VB芯片解密STM32F105R8单片机破解多少钱?
STM32F105解密STM32F105VB芯片解密STM32F105R8单片机破解 STM32F105芯片Cortex-M3单片机解密: [凯基迪科技] STM32F105R8解密 | STM32F ...
- JMeter学习-038-JMeter Linux 环境配置
1.1.下载 Download URL:http://mirrors.tuna.tsinghua.edu.cn/apache//jmeter/binaries/apache-jmeter-3.0.tg ...
随机推荐
- HanLP《自然语言处理入门》笔记--1.新手上路
1. 新手上路 自然语言处理(Natural Language Processing,NLP)是一门融合了计算机科学.人工智能及语言学的交叉学科,它们的关系如下图所示.这门学科研究的是如何通过机器学习 ...
- Shell使用技巧之逐行读取
重定向读取 #!/bin/bash while read line do echo $line done < /etc/passwd 管道读取 #!/bin/bash cat /etc/pass ...
- 文件系统(01):基于SpringBoot框架,管理Excel和PDF文件类型
本文源码:GitHub·点这里 || GitEE·点这里 一.文档类型简介 1.Excel文档 Excel一款电子表格软件.直观的界面.出色的计算功能和图表工具,在系统开发中,经常用来把数据转存到Ex ...
- Hibernate(五)
================================criteria(QBC)查询========================QBC,(容器)又名对象查询:采用对象的方式(主要是cri ...
- python——3种字符串反转方法
在学习过程中,总结了3种字符串反转方法: 1.切片法 这种方法最为简便 str='abad' print(str[::-1]) · 用切片操作,将字符串以步长-1重新整理,即 'str[-1],str ...
- thinkphp3关闭Runtime中的日志方法
将LOG_LEVEL允许记录的日志级别设置为空,则不会记录日志
- Codevs 1205 单词反转(Vector以及如何输出string)
题意:倒序输出句子中的单词 代码: #include<cstdio> #include<iostream> #include<string> #include< ...
- Java程序员必备英文单词
列表中共有769个单词,这些单词是从JDK.Spring.SpringBoot.Mybatis的源码中解析得到,按照在源码中出现的频次依次排列,页面中的单词是出现频次大于1000的.单词的音标.翻译结 ...
- Linux 性能分析 工具命令
背景知识:具备背景知识是分析性能问题时需要了解的.比如硬件 cache:再比如操作系统内核.应用程序的行为细节往往是和这些东西互相牵扯的,这些底层的东西会以意想不到的方式影响应用程序的性能,比如某些程 ...
- HSRP 详解
简介 HSRP(Hot Standby Router Protocol 热备份路由器协议)是Cisco的专有协议.HSRP把多台路由器组成一个“热备份组”,形成一个虚拟路由器.这个组内只有一个路由器是 ...