In the past year, I have been developing with VUE, but I always remember React. Recently, he tried to react again. Industry always has the vue good or react better to discuss is the most beautiful language ha ha ha ha ha (like PHP), I think is quite good, vue instruction is really sweet, react all components of the thought is really high (now has hooks blessing, function also more fragrant component). You taste, you fine taste.

Back to the point. In short, if you want to learn a framework language, you must first have the outline foundation to learn. React create-React-app (CRA for short) is a great solution to this problem.

CRA provides a service out of the box, with a number of excellent projects (such as Webpack, Babel, Eslint) built in by default to support applications. Whether you use React or another library, the Create React App lets you focus on code instead of building tools.

However, in real application development, the CRA default configuration may not meet our business needs, so the goal of this article is to effectively extend CRA. Let’s start CRA’s wonderful journey together


Initialize the project

To better standardize collaborative team development, use Typescript. TypeScript is a superset of JavaScript types that can be compiled into pure JavaScript.

To Create a new Create React App project using TypeScript, you can run:

$ npx create-react-app my-react-app-ts --typescript
Copy the code

How do I extend the default built-in Webpack?

If you are not satisfied with the build tools and configuration options, the official eject script directive directly ejects the entire configuration to be maintained in the business project. Note That this operation is irreversible and cannot be hidden once the configuration file is exposed.

$ npm run eject
Copy the code

Obviously, eject defeats CRA’s intent to focus on code rather than build. Is there a way to make custom changes to the default CRA WebPack configuration without eject, and then compile the project based on that configuration? So the React community has react-app-Rewired.

React-app-rewired this tool can modify CRA’s built-in Webpack configuration without eject or creating additional react-scripts, and then you have all the features of CRA, And you can customize webPack plugins, loaders, and so on to suit your business needs.

Additionally, customize-cra (for [email protected] above) AIDS with a set of CRA2.0 configurations for customizing react-app-Rewired core functionality.

1) install react-app-rewired (for webpack4.0)

$ npm install react-app-rewired customize-cra --save-dev
Copy the code

2) Create a config-override.js file in the root directory

/* [email protected] the following version */ module.exports =function override(config, env) {
    //do stuff with the webpack config...
    returnconfig; } /* [email protected] */ const {override, overrideDevServer, addWebpackAlias} = require('customize-cra');
    
module.exports = {
    webpack: override(
        addWebpackAlias({
            The '@': path.resolve(__dirname, '. '.'src')
        })
    ),
    devServer: overrideDevServer()
};
Copy the code

3) Modify the package.json file

"scripts": {
    "start": "react-app-rewired start"
},
Copy the code

How to read variable values in different environments?

Generally, from development to release, three environments, FAT, UAT and PROD will be passed, and the corresponding value of the same variable is different in different environments. For example, if the interface baseURL is a, B, and C in three different environments, how can it automatically read different variable values according to different environments when packaging by environment? Thus, dotenV-CLI emerged in the community.

1) Install Dotenv – CLI

$ npm install dotenv-cli --save-dev
Copy the code

2) Create.env.fat,.env.uat,.env.prod respectively in the root directory

3) Modify the package.json file

"scripts": {
    "serve:fat": "dotenv -e .env.fat react-app-rewired start",
    "serve:uat": "dotenv -e .env.uat react-app-rewired start",
    "serve:prod": "dotenv -e .env.prod react-app-rewired start",
    "build:fat": "dotenv -e .env.fat react-app-rewired build",
    "build:uat": "dotenv -e .env.uat react-app-rewired build",
    "build:prod": "dotenv -e .env.prod react-app-rewired build",
},
Copy the code

How to standardize git commit information?

Usually regulate this kind of thing, the human agreement to perform must be not the best choice, for human error operation can not control. It is most appropriate to introduce tool automation validation in a multi-person collaborative development team. Commit successfully. Use Git hooks to check commit information before commit.

1) Install Commitizen, CZ-Conventional – Changelog, and YORkie

$ npm install commitizen cz-conventional-changelog yorkie --save-dev
Copy the code

2) Create verify-commit-msg.ts in the root directory

const chalk = require('chalk');
const msgPath = process.env.GIT_PARAMS;
const msg = require('fs').readFileSync(msgPath, 'utf-8').trim(); const commitRE = /^(revert: )? (feat|fix|improvement|docs|style|refactor|perf|test|build|workflow|ci|chore|revert)(\(.+\))? : {1, 50} /;if(! commitRE.test(msg)) { console.log(); console.error( `${chalk.bgRed.white(' ERROR ')} ${chalk.red(`invalid commit message format.`)}\n\n` +
    chalk.red(`  Proper commit message format is required for automated changelog generation. Examples:\n\n`) +
    `    ${chalk.green(`feat(compiler): add 'comments' option`)}\n` +
    `    ${chalk.green(`fix(v-model): handle events on blur (close #28)`)}\n\n` +
    chalk.red(`  See .github/COMMIT_CONVENTION.md for more details.\n`) +
    chalk.red(`  You can also use ${chalk.cyan(`npm run commit`)} to interactively generate a commit message.\n`)
  );
  process.exit(1)
}
Copy the code

3) Modify package.json

"scripts": {
    "commit": "git-cz"
},
"gitHooks": {
    "commit-msg": "node scripts/verify-commit-msg.ts"
},
"config": {
    "commitizen": {
        "path": "cz-conventional-changelog"
    }
}
Copy the code

4)

$ npm run commit
Copy the code

How to import SCSS preprocessor & import SCSS common style file

To use sass, as detailed in the OFFICIAL CRA documentation, first install Node-sass

$ npm install node-sass --save-dev
Copy the code

Change the suffix of all *.css files to *.scss or *.sass, and the files will compile automatically.

To share variables between Sass files, you can use Sass imports. For example, SRC/app.scss and other component style files might contain @import “./shared. SCSS “; Variables defined in.

But as the business is full and the code volume increases, it’s just too tiring and silly to manually import the common style file for every SCSS file (hahaha). This annoyance is usually solved by introducing sas-Resources-loader, but what about rewired sas-Resources-loader in CRA? Let’s return to customize-cra.

1) Install sass-resources-loader

$ npm install sass-resources-loader --save-dev
Copy the code

2) Modify config-overrides. Js

const {override, adjustStyleLoaders} = require('customize-cra');
module.exports = {
  webpack: override(
    adjustStyleLoaders(rule => {
      if (rule.test.toString().includes('scss')) {
        rule.use.push({
          loader: require.resolve('sass-resources-loader'),
          options: {
            resources: './src/styles/shared.scss'}}); }}}));Copy the code

How to achieve mobile adaptive?

Since MY actual working direction is mainly mobile terminal H5, I pay special attention to the responsive change of page layout on mobile terminal for different models of different sizes. Usually, page adaptation can be achieved through REM or VWVH, but the design manuscript given by designers to the development is designed with fixed width and height pixels PX, so how to convert PX into REM or VWVH units according to the design ratio? Will manual conversion or the introduction of common mixin functions feel tedious? Imagine if webpack were to do this. Taking PX to VH as an example, how can it be rewired automatically in CRA?

1) Install postCSs-px-to-viewPort

$ npm install postcss-px-to-viewport --save-dev
Copy the code

2) Modify config-overrides. Js

const {override, addPostcssPlugins} = require('customize-cra');

module.exports = {
  webpack: override(
    addPostcssPlugins([
      require('postcss-px-to-viewport')({
        unitToConvert: 'px',
        viewportWidth: 1024,
        viewportHeight: 768,
        unitPrecision: 5,
        propList: [The '*'],
        viewportUnit: 'vh',
        fontViewportUnit: 'vh',
        selectorBlackList: [],
        minPixelValue: 1,
        mediaQuery: false,
        replace: true,
        exclude: [],
        landscape: false,
        landscapeUnit: 'vh',
        landscapeWidth: 568
      })
    ])
  )
};
Copy the code

conclusion

So far, this article has shown how to extend CRA’s basic WebPack configuration. Everyone can customize it for their business needs, such as the esLint rule, prettier format specification, and so on.

Of course, a complete SPA application, of course, the concept of routing, can be learned through the react-Router official, after V4, according to the idea of routing components should be easier to understand. I won’t go into details here.

Lastly, react-hooks, which are enhancements to once-functional components that have the same capabilities as class components but significantly less code. Later is not can loudly say: everything is a function of the component 😊.

Thank you for reading