关于react.js:createreactapp-一些常用的自定义配置

5次阅读

共计 5334 个字符,预计需要花费 14 分钟才能阅读完成。

yarn 装置依赖包报错

在我的项目目录下运行 yarn, 报错如下

yarn install v1.7.0
[1/4] Resolving packages...
[2/4] Fetching packages...
info There appears to be trouble with your network connection. Retrying...
error An unexpected error occurred: "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.0.0.tgz: connect ETIMEDOUT 104.16.21.35:443".
info If you think this is a bug, please open a bug report with the information provided in "F:\\await\\react-rabc\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

提醒很显著,网络连接超时,咱们更换一下源地址就行了

npm 设置为 淘宝源

npm config set registry https://registry.npm.taobao.org
npm config set disturl https://npm.taobao.org/dist

yarn 设置为 淘宝源

yarn config set registry https://registry.npm.taobao.org --global
yarn config set disturl https://npm.taobao.org/dist --global

我的项目中如果用的是 sass,须要下载 node-sass,这个依赖包下载是相当的慢,能够独自设置源地址

yarn config set sass-binary-site http://npm.taobao.org/mirrors/node-sass
npm config set sass-binary-site http://npm.taobao.org/mirrors/node-sass

最初删除 node_modules,从新下载就行了

IE10 下报错, Map 未定义

yarn add react-app-polyfill

入口文件第一行引入

// This must be the first line in src/index.js
import 'react-app-polyfill/ie9'

react-app-polyfill

webpack 增加 alias

config/modules.js文件中的 webpackAliasesalias是解析我的项目根目录下的 tsconfig.json 或者 jsconfig.json 来返回的,有点简单

能够间接在 webpack.config.jsresolve.alias字段中的开端新增字段

resolve: {
  // ...
  alias: {
    // ...
    '@': path.resolve(__dirname, '../src')
  }
}

解决跨域,反向代理配置

1、装置依赖

yarn add http-proxy-middleware

2、在 src 目录下新建 setupProxy.js 文件

const {createProxyMiddleware} = require('http-proxy-middleware')
module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:6000', // 申请接口地址
      changeOrigin: true,
      pathRewrite: {'^/api': '/'}
    })
  )
}

我的项目次要文件门路配置

包含我的项目入口文件、动态目录、我的项目构建输入目录、配置 proxy 文件 …

config/paths.js 文件配置,挑出几个最罕用的

module.exports = {dotenv: resolveApp('.env'), // 我的项目环境变量文件
  appBuild: resolveApp('dist'), // 我的项目构建输入目录,默认 build
  appPublic: resolveApp('public'), // 动态目录
  appHtml: resolveApp('public/index.html'), // index.html
  appIndexJs: resolveModule(resolveApp, 'src/index'), // 我的项目入口文件
  proxySetup: resolveApp('src/setupProxy.js') // 配置 proxy 文件
}

敞开主动开启浏览器配置

scripts/start.js 文件,正文掉 openBrowser(urls.localUrlForBrowser) 即可
或者设置环境变量 BROWSERnone

批改 webpack output.publicPath

如果我的项目不是部署在动态服务器根目录下会用到,间接在 package.json 中配置 homepage 字段 `

{"homepage": "/e-admin/"}

或者在命令行中应用 PUBLIC_URL 字段

{
  "script": {"build": "cross-env PUBLIC_URL=/e-admin/ node scripts/build.js"}
}

因为各平台设置环境变量的形式不同,这里应用 cross-env 来抹平差别

eslint 配置

能够间接在 package.json 中的 eslintConfig 字段配置。

在根目录下新建.eslint.js(或者.eslintrc)配置文件,而后在命令行中设置EXTEND_ESLINT

{
  "script": {"build": "cross-env EXTEND_ESLINT=true node scripts/build.js"}
}

装璜器 Decorators 配置

开发中会有很多高阶组件以及 redux 的 connect 来包裹组件,应用 Decorators 写法会直观许多

  • 先装置 babel 插件
yarn add @babel/plugin-proposal-decorators
  • babel 配置,在 plugins 中增加
{
  "plugins": [
    [
      "@babel/plugin-proposal-decorators",
      {"legacy": true}
    ]
  ]
}
  • 实现下面配置后,编译就不会报错了,代码能失常运行,然而编辑器(这是应用 VSCode)却报错了,咱们须要做额定的配置

    • 在根目录下新建 jsconfig.json 文件

      {
        "compilerOptions": {"experimentalDecorators": true}
      }
    • 关上 VSCodesetting.json 文件,增加以下属性

      "javascript.implicitProjectConfig.experimentalDecorators": true

create-react-app 的 babel 配置默认是在 package.json 中的,能够独自放到根目录下(.babelrc 或者 babel.config.js)

引入 antd

antd 的 JS 代码默认反对基于 ES modules 的 tree shaking,即按需引入,只是款式的引入有些区别

1、间接引入,款式间接用编译后的antd.css

import {Button} from 'antd'
import 'antd/dist/antd.css'

function App() {
  return (<Button type="primary"> 按钮 </Button>)
}

简略粗犷,然而没法对立批改一些全局的色彩

2、引入 less

  • 装置依赖

    yarn add less less-loader
  • wepack.config.js配置,默认的 rules 曾经蕴含 csssass,先找到上面的正则

    // style files regexes
    const cssRegex = /\.css$/;
    const cssModuleRegex = /\.module\.css$/;
    const sassRegex = /\.(scss|sass)$/;
    const sassModuleRegex = /\.module\.(scss|sass)$/;
    // 加上匹配 less 文件的正则
    const lessRegex = /\.less$/;
    const lessModuleRegex = /\.module\.less$/;

    而后加上 loader 配置,在 sass-loader 配置上面加上 less-loader 的配置

    // Adds support for CSS Modules, but using SASS
    // using the extension .module.scss or .module.sass
    {
      test: sassModuleRegex,
      use: getStyleLoaders(
        {
          importLoaders: 3,
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modules: {getLocalIdent: getCSSModuleLocalIdent,},
        },
        'sass-loader'
      ),
    },
    // 在上面加上 less-loader 配置
    {
      test: lessRegex,
      exclude: lessModuleRegex,
      use: getStyleLoaders(
        {
          importLoaders: 2,
          sourceMap: isEnvProduction && shouldUseSourceMap,
        },
        'less-loader'
      ),
      sideEffects: true,
    },
    // Adds support for CSS Modules, but using less
    // using the extension .module.less
    {
      test: lessModuleRegex,
      use: getStyleLoaders(
        {
          importLoaders: 2,
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modules: {getLocalIdent: getCSSModuleLocalIdent,}
        },
        'less-loader'
      ),
    },

    找到 getStyleLoaders 办法,做如下批改:

    // 将 if (preProcessor) {} 中的代码替换,实际上就是判断是 `less-loader` 就生成针对 less 的 options
    if (preProcessor) {
      let preProcessorRule = {loader: require.resolve(preProcessor),
        options: {sourceMap: true}
      }
      if (preProcessor === 'less-loader') {
        preProcessorRule = {loader: require.resolve(preProcessor),
          options: {
            sourceMap: true,
            lessOptions: { // 如果应用 less-loader@5,须要移除 lessOptions 这一级
              javascriptEnabled: true,
              modifyVars: {
                'primary-color': '#346fff', // 全局主色
                'link-color': '#346fff' // 链接色
              }
            }
          }
        }
      }
      loaders.push(
        {loader: require.resolve('resolve-url-loader'),
          options: {sourceMap: isEnvProduction && shouldUseSourceMap,},
        },
        preProcessorRule
      );
    }
  • import 'antd/dist/antd.css' 换成import 'antd/dist/antd.less'

    通过下面的配置后,能够间接批改 less 变量来批改全局色彩、间距等,所有变量

    当然如果在配置文件中笼罩 less 变量有些麻烦,能够间接间接新建独自的 less 文件来笼罩默认变量

    @import '~antd/lib/style/themes/default.less';
    @import '~antd/dist/antd.less';
    @import 'customer-theme-file.less'; // 用于笼罩默认变量

    然而这种形式会加载所有组件的款式,没法做到按需加载

3、按需加载

  • 装置依赖

    yarn add babel-plugin-import
  • babel 配置

    "plugins": [
      [
        "babel-plugin-import",
        {
          "libraryName": "antd",
          "libraryDirectory": "es",
          "style": true
        }
      ]
    ]
  • 去掉 import 'antd/dist/antd.less' 的引入,当初引入组件就会附带引入对应组件的款式了

参考链接:

  • Create React App 官网文档
  • Create React App 中文文档
  • Ant Design
正文完
 0