create-react-app综合问题

2022-08-28 09:38:46

一、 快速开始:

  • 全局安装脚手架:
npm install -g create-react-app复制代码复制代码
  • 通过脚手架搭建项目:
  <项目名称>复制代码复制代码
  • 开始项目:
cd <项目名>npm run start复制代码复制代码

二、 查看项目 package.json 信息

2.1 package.json 一览

{
  ......"homepage":".","dependencies": {"react":"^16.4.0","react-dom":"^16.4.0","react-scripts":"1.1.4"
  },"scripts": {"start":"react-scripts start","build":"react-scripts build","test":"react-scripts test --env=jsdom","eject":"react-scripts eject"
  }
}复制代码

2.2 可用脚本命令说明:

首先说明:通过npm run 执行下面命令实际上是运行 node_modules/react-srcipt/script 下对应的脚本文件; npm run start: 开始项目,运行项目后可通过 http://localhost:3000 访问项目; npm run build: 项目打包,在生产环境中编译代码,并放在build目录中;所有代码将被正确打包,并进行优化、压缩同时使用hash重命名文件;执行该命令前需要在 package.json 中新增条配置"homepage": "."(上面配置文件已给出), 同时build后的项目需要在服务器下才能访问;否则打开的将是空白页面; npm run test: 交互监视模式下启动测试运行程序; npm run eject: 将隐藏的配置导出;需要知道的是create-react-app脚手架本质上是使用react-scripts进行配置项目,所有配置文件信息都被隐藏起来(node_modules/react-scripts);当需要手动修改扩展webpack配置时有时就需要将隐藏的配置暴露出来;特别需要注意的是该操作是一个单向操作,一旦使用eject,那么就不能恢复了(再次将配置隐藏);


四、 添加对 less 的支持

4.1 方法一:暴露配置并进行修改

  • 暴露配置文件:
npm run eject说明: 执行eject脚本后,项目下会新增或对部分配置文件进行修改;项目下 script 目录存放着脚本文件, config 目录下存放着配置文件复制代码
  • 下载安装依赖:less-loader less
npm install less-loader less -dev复制代码
  • 修改 config 目录下的webpack配置文件:
    • 需同时修改下面的两个文件:
    • 开发环境下的配置文件:webpack.config.dev.js
    • 生产环境下的配置文件:webpack.config.prod.js
    • 两个文件的修改内容相同,对应修改内容如下(三处需要进行修改)
复制代码
{
+test: /\.(css|less)$/,
    use: [
        require.resolve('style-loader'),
        {
            loader: require.resolve('css-loader'),
            options: {
+           importLoaders: 2,
        },
        },
        { .... },
+       {
+         loader: require.resolve('less-loader'),
+       }
    ],
}
复制代码复制代码

4.2 方法二: 使用 react-app-rewired 对 webpack 进行自定义配置(覆盖或添加)

4.2.1 react-app-rewired 老版本配置方法

react-app-rewired 的使用

  • 安装 react-app-rewired 插件
npm install react-app-rewired --save-dev

修改 package.json 中的脚本命令:修改如下"scripts": {
+"start":"react-app-rewired start",
+"build":"react-app-rewired build",
+"test":"react-app-rewired test --env=jsdom",
+"eject":"react-app-rewired eject"
  }复制代码
  • 在项目根目录下(和 package.json 同级)新建配置文件 config-overrides.js ,并添加如下内容
module.exports =function override(config, env) {  // 在这里添加配置return config;}复制代码


修改配置文件 config-overrides.js 使得项目能够支持 less

    • 安装依赖包 react-app-rewire-less,通过该依赖包来实现对 less 的支持:
# 说明: 这里不再需要额外单独安装依赖包:less-loader  lessnpm install react-app-rewire-less --save复制代码
  • 修改 config-overrides.js 配置文件
  • + const rewireLess = require('react-app-rewire-less');
    module.exports =function override(config, env) {
    +  // 只需要一条配置信息即可实现对less的支持
    +  config = rewireLess(config, env);return config;
    }复制代码

4.2.2 react-app-rewired 新版本配置方法( >=2.1.0 )

react-app-rewired 的使用: 使用上和旧版本基本一样只是在配置上需要额外通过 customize-cra 插件来实现


  • 安装 react-app-rewired customize-cra 插件
复制代码
  1. 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-app-rewired eject"
  }复制代码
  • 在项目根目录下(和 package.json 同级)新建配置文件 config-overrides.js ,并添加如下内容
复制代码
const { override } = require('customize-cra');module.exports = override();复制代码

修改配置文件 config-overrides.js 使得项目能够支持 less

  • 安装依赖: less less-loader
复制代码
  1. npm install less less-loader --save-dev
  • 修改 config-overrides.js 配置文件: addLessLoader
复制代码
+ const { override, addLessLoader } = require('customize-cra');
module.exports = override(
+  addLessLoader({
+    strictMath:true,
+    noIeCompat:true
+  })
);复制代码

五、 在 create-react-app 中使用Antd

安装 antd 依赖包:
npm install antd --save
复制代码
5.1 方法一: 直接导入所有样式, 并引用相应组件
引入 antd 组件之前需要先引入 antd 样式( 在项目入口引入所有样式 ):
import antd/dist/antd.css
复制代码
在项目中引入 antd 组件

import { Button } from'antd';复制代码

5.2 方法二: 按需加载

  • 上面引入组件和样式的方式,会一次性加载所有样式并引入组件中的所有相应模块;
  • 这种引入方式将会影响到应用的网络性能;
  • 相应的就需要改变引入组件和样式的方式,实现样式和组件的按需加载;
  • 下面将介绍三种按需加载组件样式的方法:


5.2.1 引入独立的组件和样式

import Button from'antd/lib/button';i
mport'antd/lib/button/style';

// 或者通过import antd/lib/button/style/css 进行加载样式复制代码

5.2.2 通过暴露配置并使用 babel-plugin-import 插件实现按需加载

  • babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件

    • 暴露配置

npm run eject

安装插件:
npm install babel-plugin-import --save-dev
复制代码
修改 package.json"babel": {"presets": ["react-app"
  ],"plugins": [
+   ["import", {"libraryName":"antd","libraryDirectory":"es","style":"css" }]
  ]
},复制代码
  • 配置完后可直接导入 antd 的组件,不再需要另外引入css样式;
复制代码
  1. import { Button } from 'antd';

5.2.2 react-app-rewired + babel-plugin-import 实现按需加载(官网推荐)

react-app-rewired 老版本配置方法
  • babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件;
  •  react-app-rewired 的使用在第四节已经有了详细的描述这里不在赘述;
  • 下文直接通过修改 config-overrides.js 配置来实现 antd 的按需加载


  • 安装依赖包:babel-plugin-import
  1. npm install babel-plugin-import --save-dev
  • 修改配置文件 config-overrides.js: 通过 injectBabelPlugin 插件实现 babel 的添加
复制代码
+ const { injectBabelPlugin } = require('react-app-rewired');
module.exports =function override(config, env) {
+  config = injectBabelPlugin(['import', { libraryName:'antd', libraryDirectory:'es', style:'css' }], config);return config;
};复制代码
react-app-rewired 新版本配置方法( >=2.1.0 )
    • 新版本可以直接通过 customize-cra 的 fixBabelImports 方法实现按需加载
复制代码
+const { override, addLessLoader, fixBabelImports } = require('customize-cra');
module.exports = override(
 addLessLoader({
   strictMath:true,
   noIeCompat:true
 }),
+ fixBabelImports('import', { libraryName:'antd', libraryDirectory:'es', style:'css' }),
);复制代码

5.3 通过 react-app-rewired 扩展 webpack 来实现 antd 自定义主题

    • 主要通过利用了 less-loader 的 modifyVars 参数来进行主题配置
    • 下面是基于第四节中对 less 的配置的基础上添加 modifyVars 参数来实现自定义主题的目的

5.3.1 react-app-rewired 老版本配置方法

    • 修改 config-overrides.js 配置文件
复制代码
const rewireLess = require('react-app-rewire-less');
const { injectBabelPlugin } = require('react-app-rewired');
module.exports =function override(config, env) {
  // 扩展 webpack ==> 支持less
  config = rewireLess(config, env);
  // 配置 less-loader 加载参数
+ config = rewireLess.withLoaderOptions({modifyVars: {"@primary-color":"#1DA57A" },})(config, env);
  // antd 按需加载配置
  config = injectBabelPlugin(['import',
  { libraryName:'antd', libraryDirectory:'es', style:true }], config);return config;
}复制代码

5.3.2 react-app-rewired 新版本配置方法( >=2.1.0 )

  • addLessLoader 必须添加javascriptEnabled: true
  • fixBabelImports 实现对 antd 按需加载时需要设置style: true


const { override, addLessLoader, fixBabelImports } = require('customize-cra');
module.exports = override(
  addLessLoader({
    strictMath:true,
    noIeCompat:true,
+   javascriptEnabled:true,
+   modifyVars: {"@primary-color":"#1DA570" }
  }),
+  fixBabelImports('import', { libraryName:'antd', libraryDirectory:'es', style:true }),
);

---------------------复制代码


六、 实现对修饰器的支持: 实现对 babel 插件的使用

安装插件# 如果你的 Babel < 7.x 则安装
 babel-plugin-transform-decorators-legacy
npm install --save-dev babel-plugin-transform-decorators-legacy# 如果你的 Babel >= 7.x 则应该安装
 @babel/plugin-proposal-decorators
npm install --save-dev @babel/plugin-proposal-decorators复制代码

6.1 方法一: 暴露配置并进行修改

  • 假设当前 Babel >= 7.x, 如果你的 Babel < 7.x 则需要将["@babel/plugin-proposal-decorators", {"legacy": true}] 修改为["transform-decorators-legacy"]
  • 暴露配置

npm run eject复制代码
修改 package.json"babel": {"presets": ["react-app"  ],"plugins": [
      ["@babel/plugin-proposal-decorators", 
    {"legacy":true}
        ]  
    ]
},复制代码

6.2 方法二: 使用 react-app-rewired 对 webpack 进行自定义配置(覆盖或添加)

6.2.1 react-app-rewired 老版本配置方法

  • react-app-rewired 的使用参考第四节:
  • 修改 config-overrides.js 配置文件
// 导入添加babel插件的函数
+const { injectBabelPlugin } = require('react-app-rewired');
module.exports =function override(config, env) {
+ config = injectBabelPlugin(["@babel/plugin-proposal-decorators", {"legacy":true}], config)return config;
};复制代码

6.2.2 react-app-rewired 新版本配置方法( >=2.1.0 )

  • react-app-rewired 的使用参考第四节:
  •  修改 config-overrides.js 配置文件:
  • 下面给出了三种配置 babel 插件的方法,
  •  addBabelPlugin 和 addBabelPlugins 用法类似 useBabelRc 是允许项目使用
  •  .babelrc 配置文件进行配置
+const {
+  override, addLessLoader, fixBabelImports,
+  addBabelPlugin, addBabelPlugins, useBabelRc
+} = require('customize-cra');
module.exports = override(
 addLessLoader({
   strictMath:true,
   noIeCompat:true,
   javascriptEnabled:true,
   modifyVars: {"@primary-color":"#1DA570" }
 }),
 fixBabelImports('import', { libraryName:'antd', libraryDirectory:'es', style:true }),
 
+ addBabelPlugin(["@babel/plugin-proposal-decorators", {"legacy":true}]),
 
+ // ...addBabelPlugins(
+ //  ["@babel/plugin-proposal-decorators", {"legacy":true}]
+ // ),
+ // useBabelRc(),
);
 
复制代码复制代码


七、 eslint 配置

7.1 暴露配置并进行修改

    • 执行脚本 暴露配置文件
npm run eject复制代码
  • 通过修改 package.json 文件添加对 eslint 的扩展配置
复制代码
..."eslintConfig": {
  // 默认继承 脚手架自带的 eslint 配置"extends":"react-app",
  // 在这里扩展新增配置"rules":{
     // 设置规则,具体看官网用户指南下的规则文档"eqeqeq":"off"
  }
 }复制代码

7.2 使用 react-app-rewired 对 webpack 进行自定义配置(覆盖或添加)

7.2.1 react-app-rewired 老版本配置方法

  • react-app-rewired 的使用参考第四节:
  • 安装依赖:
  • npm install react-app-rewired react-app-rewire-eslint --save


  • 修改 config-overrides.js 配置文件


+ const rewireEslint = require('react-app-rewire-eslint');
module.exports =function override(config, env) {
+  config = rewireEslint(config, env);return config;
}复制代码
  • 在根目录下创建 .eslintrc 并自定义eslint配置
复制代码


{"rules": {
      // 设置规则,具体看官网用户指南下的规则文档"eqeqeq":"off"
  }
}
复制代码复制代码

7.2.2 react-app-rewired 新版本配置方法( >=2.1.0 )

  • react-app-rewired 的使用参考第四节:
  • 修改 config-overrides.js 配置文件: 通过 useEslintRc 启用 .eslintrc 配置文件
 const { override, useEslintRc } = require('customize-cra');module.exports = override(+ useEslintRc(),);复制代码
  • 在根目录下创建 .eslintrc 并自定义eslint配置
复制代码
{"rules": {
      // 设置规则,具体看官网用户指南下的规则文档"eqeqeq":"off"
  }
}
复制代码复制代码




const path = require('path')//配置vw// const postcssAspectRatioMini = require('postcss-aspect-ratio-mini');// const postcssPxToViewport = require('postcss-px-to-viewport');// const postcssWriteSvg = require('postcss-write-svg');// // const postcssCssnext = require('postcss-cssnext');// const postcssPresetEnv = require('postcss-preset-env');// const postcssViewportUnits = require('postcss-viewport-units');// const cssnano = require('cssnano');// module.exports =function override(config, env) {//     config.resolve.alias = {//         ...config.resolve.alias,//'@': path.resolve(__dirname,'src'),//     };//return config;// };// const rewireEslint = require("react-app-rewire-eslint");

使用 customize-cra 配置  const {      useEslintRc,    override ,    addWebpackAlias,     addWebpackResolve,     addPostcssPlugins} = require('customize-cra');//function overrideEslintOptions(options) {//   //do stuff with the eslint options...//return options;// }module.exports = {    webpack:override(
       // 配置别名        addWebpackAlias({            ["@"]: path.resolve(__dirname,'src'),        }),
        // 配置使用viewport (vw) 插件 -- start        addPostcssPlugins([require('postcss-flexbugs-fixes'),        require('postcss-preset-env')({            autoprefixer: {                flexbox:'no-2009',            },            stage: 3,        }),        require('postcss-aspect-ratio-mini')({}),        require('postcss-px-to-viewport')({            viewportWidth: 750, // (Number) The width of the viewport.            viewportHeight: 1334, // (Number) The height of the viewport.            unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.            viewportUnit:'vw', // (String) Expected units.            selectorBlackList: ['.ignore','.hairlines'], // (Array) The selectors to ignore and leave as px.            minPixelValue: 1, // (Number) Set the minimum pixel value to replace.            mediaQuery:false // (Boolean) Allow px to be convertedin media queries.        }),        require('postcss-write-svg')({            utf8:false        }),        require('postcss-viewport-units')({}),        require('cssnano')({            preset:"advanced",            autoprefixer:false,"postcss-zindex":false        })]),
        // 配置使用viewport (vw) 插件 -- start        // 启用eslint
        //useEslintRc(),    ),    devServer:function(configFunction) {        // Return the replacementfunctionfor create-react-app to use to generate the Webpack        // Development Server config."configFunction" is thefunction that would normally have        // been used to generate the Webpack Development server config - you can use it to create        // a starting configuration tothen modify instead of having to create a config from scratch.returnfunction(proxy, allowedHost) {          // Create the default config by calling configFunction with the proxy/allowedHost parameters          const config = configFunction(proxy, allowedHost);               // Change the https certificate options to match your certificate, using the .env file to          //set the file paths & passphrase.          /* const fs = require('fs');          config.https = {            key: fs.readFileSync(process.env.REACT_HTTPS_KEY,'utf8'),            cert: fs.readFileSync(process.env.REACT_HTTPS_CERT,'utf8'),            ca: fs.readFileSync(process.env.REACT_HTTPS_CA,'utf8'),            passphrase: process.env.REACT_HTTPS_PASS          }; */           /*  config.proxy = {"/api": {"target":"http://lemonof.com:82","pathRewrite": {"^/api" :""}                }            } */          // Return your customised Webpack Development Server config.return config;        };      },}复制代码



// 使用普通 react-app-rewire-postcs  配置viewport

const path = require('path')//配置vw// const postcssAspectRatioMini = require('postcss-aspect-ratio-mini');// const postcssPxToViewport = require('postcss-px-to-viewport');// const postcssWriteSvg = require('postcss-write-svg');// // const postcssCssnext = require('postcss-cssnext');// const postcssPresetEnv = require('postcss-preset-env');// const postcssViewportUnits = require('postcss-viewport-units');// const cssnano = require('cssnano');// module.exports =function override(config, env) {//     config.resolve.alias = {//         ...config.resolve.alias,//'@': path.resolve(__dirname,'src'),//     };//return config;// };// const rewireEslint = require("react-app-rewire-eslint");const {      useEslintRc,    override ,    addWebpackAlias,     addWebpackResolve,     addPostcssPlugins} = require('customize-cra');//function overrideEslintOptions(options) {//   //do stuff with the eslint options...//return options;// }module.exports = {        webpack:function(config, env) {
        // 配置别名        config.resolve.alias = {            ...config.resolve.alias,'@': path.resolve(__dirname,'src'),        };

       // viewport(开始) ---start        require('react-app-rewire-postcss')(config, {            plugins: loader => [                require('postcss-flexbugs-fixes'),                require('postcss-preset-env')({                    autoprefixer: {                        flexbox:'no-2009',                    },                    stage: 3,                }),                require('postcss-aspect-ratio-mini')({}),                require('postcss-px-to-viewport')({                    viewportWidth: 750, // (Number) The width of the viewport.                    viewportHeight: 1334, // (Number) The height of the viewport.                    unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.                    viewportUnit:'vw', // (String) Expected units.                    selectorBlackList: ['.ignore','.hairlines'], // (Array) The selectors to ignore and leave as px.                    minPixelValue: 1, // (Number) Set the minimum pixel value to replace.                    mediaQuery:false // (Boolean) Allow px to be convertedin media queries.                }),                require('postcss-write-svg')({                    utf8:false                }),                require('postcss-viewport-units')({}),                require('cssnano')({                    preset:"advanced",                    autoprefixer:false,"postcss-zindex":false                })            ]        });
       // viewport(开始) ---end        // config = rewireEslint(config, env, overrideEslintOptions);return config;    },    devServer:function(configFunction) {        // Return the replacementfunctionfor create-react-app to use to generate the Webpack        // Development Server config."configFunction" is thefunction that would normally have        // been used to generate the Webpack Development server config - you can use it to create        // a starting configuration tothen modify instead of having to create a config from scratch.returnfunction(proxy, allowedHost) {          // Create the default config by calling configFunction with the proxy/allowedHost parameters          const config = configFunction(proxy, allowedHost);               // Change the https certificate options to match your certificate, using the .env file to          //set the file paths & passphrase.          /* const fs = require('fs');          config.https = {            key: fs.readFileSync(process.env.REACT_HTTPS_KEY,'utf8'),            cert: fs.readFileSync(process.env.REACT_HTTPS_CERT,'utf8'),            ca: fs.readFileSync(process.env.REACT_HTTPS_CA,'utf8'),            passphrase: process.env.REACT_HTTPS_PASS          }; */           /*  config.proxy = {"/api": {"target":"http://lemonof.com:82","pathRewrite": {"^/api" :""}                }            } */          // Return your customised Webpack Development Server config.return config;        };      },}// webpack:function(config, env) {//     config.resolve.alias = {//         ...config.resolve.alias,//'@': path.resolve(__dirname,'src'),//     };//     require('react-app-rewire-postcss')(config, {//         plugins: loader => [//             require('postcss-flexbugs-fixes'),//             require('postcss-preset-env')({//                 autoprefixer: {//                     flexbox:'no-2009',//                 },//                 stage: 3,//             }),//             require('postcss-aspect-ratio-mini')({}),//             require('postcss-px-to-viewport')({//                 viewportWidth: 750, // (Number) The width of the viewport.//                 viewportHeight: 1334, // (Number) The height of the viewport.//                 unitPrecision: 3, // (Number) The decimal numbers to allow the REM units to grow to.//                 viewportUnit:'vw', // (String) Expected units.//                 selectorBlackList: ['.ignore','.hairlines'], // (Array) The selectors to ignore and leave as px.//                 minPixelValue: 1, // (Number) Set the minimum pixel value to replace.//                 mediaQuery:false // (Boolean) Allow px to be convertedin media queries.//             }),//             require('postcss-write-svg')({//                 utf8:false//             }),//             require('postcss-viewport-units')({}),//             require('cssnano')({//                 preset:"advanced",//                 autoprefixer:false,//"postcss-zindex":false//             })//         ]//     });//     // config = rewireEslint(config, env, overrideEslintOptions);//     useEslintRc();//return config;// },复制代码


转载于:https://juejin.im/post/5ca5bd0ee51d4564221c4cf3

  • 作者:weixin_34153893
  • 原文链接:https://blog.csdn.net/weixin_34153893/article/details/91432260
    更新时间:2022-08-28 09:38:46