In 9102 years, front-end engineering development has been well developed on the basis of NodeJS, and a variety of front-end building AIDS have emerged endlessly. ES6 compiler Babel, CSS helper postCSS/sass/less, code style detection tool ESLint/prettier/stylelint, Git AIDS husky/Lint-staged/Commitizen/Commitlint, automated build tools Webpack/gulp/Grunt, test tools Jest/Mocha, etc.

It’s a waste of time to configure so many development AIDS every time you write a project, and to maintain a set of templates that have to be updated from time to time. A handy way to configure a development environment is to use a CLI or some popular bolierplate. This article will use the Create-React-app (CRA for short) cli tool to configure Ant Design in a non-eject manner, as well as some helper tools that crA does not have built in.

Initialize the project and add typescript support

Typescript has been adopted by more and more developers and open source projects at an amazing rate in the last two years, and I’ve become a fan of Typescript circles after developing a project in Typescript. The smart hints of typescript development help eliminate the need to look up documents in most cases, and syntactical features in typescript that are not found in javascript, such as enumerations, make project organization very elegant. From Angular2 being developed in typescript by default to vue3 being rewritten in typescript, we can see that typescript is becoming more and more important in the front-end world. Unless it’s a very small project, it’s definitely wise to get typescript.

My development environment:

Node: 10.15.3 LTS

Yarn: 1.15.2

editor: visual studio code

Cra has built-in typescript support, and you only need to specify the –typescript parameter when initializing your project.

npx create-react-app my-app --typescript

# or

yarn create react-app my-app --typescript
Copy the code

If the CRA project already exists, install the following TS Types dependencies first:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

# or

yarn add typescript @types/node @types/react @types/react-dom @types/jest
Copy the code

Then rename the.js ending file to.tsx.

For more information about using TS in CRA, see the official documentation: Adding TypeScript

Configure ant design

Install ant Design dependencies

Now install and import ANTD from YARN or NPM.

$ yarn add antd
Copy the code

Configure ant Design CSS to load on demand

There are many ways to configure CSS to load on demand, which boils down to modifying the WEBpack configuration of crA. To expose the CRA Webpack configuration, run the yarn eject command to expose the webpack configuration of the project in the root directory of the project. The configuration is saved in the config folder. I remember that the configuration exposed after an earlier version of CRA, Eject, was split into webpack.config.dev.js and webpack.config.prod.js. The latest CRA configuration is incorporated into a configuration file, just a configuration file, using a calculated environment (development/producation) to dynamically generate the WebPack configuration. This way I find it more troublesome to configure, and eject is irreversible. Modifying the WebPack configuration with eject needs to be considered carefully. The nice thing about this approach is that you can modify the WebPack configuration directly, so there’s almost nothing that can’t be loaded this way.

Here I use the community’s CRA configuration solution: React-app-rewired.

Introduce react-app-rewired and modify the startup configuration in package.json. Thanks to the new [email protected] version, you’ll also need to install customize-cra.

$ yarn add react-app-rewired customize-cra
Copy the code
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test",
+ "test": "react-app-rewired test",
	"eject": "react-scripts eject"
}
Copy the code

Create a new config folder in the project root directory and add configuration to package.json:

"config-overrides-path": "config/config-overrides.js"
Copy the code

Then create a config-overrides. Js to modify the default configuration.

module.exports = function override(config, env) {
  // do stuff with the webpack config...
  return config;
};
Copy the code

Use the Babel – plugin – import

Babel-plugin-import is a Babel plug-in for loading component code and styles on demand. Now let’s try to install it and modify the config-overrides. Js file.

$ yarn add babel-plugin-import
+ const { override, fixBabelImports } = require('customize-cra');

- module.exports = function override(config, env) {
- // do stuff with the webpack config...
- return config;
-};
+ module.exports = override(
+ fixBabelImports('import', {
+ libraryName: 'antd',
+ libraryDirectory: 'es',
+ style: 'css',
+}).
+);
Copy the code

Import ant Design components in the following format.

  // src/App.js
  import React, { Component } from 'react';
- import Button from 'antd/lib/button';
+ import { Button } from 'antd';import './App.css'; class App extends Component { render() { return ( <div className="App"> <Button type="primary">Button</Button> </div> );  } } export default App;Copy the code

Finally, restart the YARN Start page. The ANTD component’s JS and CSS code will be loaded on demand, and you will not see such a warning message on the console. You can read here about the principles and other ways of loading on demand.

Custom themes

According to the requirements of configuring the topic, the less variable override function is required to customize the topic. We can introduce addLessLoader, the less related function provided in customize-cra, to help load less styles, and modify the config-overrides. Js file as follows.

$ yarn add less less-loader
Copy the code
- const { override, fixBabelImports } = require('customize-cra');
+ const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
- style: 'css',
+ style: true,
  }),
+ addLessLoader({
+ javascriptEnabled: true,
+ modifyVars: { '@primary-color': '#1DA57A' },
+}).
);
Copy the code

ModifyVars of less-Loader is used for theme configuration. For variables and other configuration methods refer to the Configuration Theme documentation.

After the modification, restart YARN start.

addsasssupport

[email protected] has built-in sass support, we just need to install the Node-sass dependency.

$ yarn add node-sass
Copy the code

You can then change the CSS file suffix in the project template to.scss. SCSS is not. Sass. Sass is yML.

addeditorconfig

Editorconfig helps us constrain the code style of multiple developers in the same project, and more importantly it is cross-editor, IDE.

To use in VS Code, you can install the EditorConfig for VS Code plugin and then CTRL + Shift + P to bring up the command panel. Type editorConfig to see the generator. editorConfig command, which will generate the initial.editorConfig file in the root directory.

Add NVMRC

Create the.nvmrc file in the project root directory and copy the results of Node -v into it. Or execute the following command directly from the project root directory.

$ node -v > .nvmrc
Copy the code

Add the gitignore

Cra already adds.gitignore by default, we can add some more like SRC /assets/videos/*. Using the VisualStudioCode plugin gitignore we can easily add other files to be ignored, such as the option to add VisualStudioCode, Windows ignore files.

Configuration linters

ESLint

ESLint can constrain the code styles of team members and find code that is likely to cause problems. After installing ESLint in vscode, you can see various errors from ESLint in the PROBLEMS panel. The built-in autoFix of ESLint works fine too, but I usually just ask Prettier to format the code when I submit it.

Cra is integrated with ESLint by default. To get the editor to correctly prompt for ESLint errors, you need to add.eslintrc.json to the project root directory. As follows:

{
  "extends": "react-app"
}
Copy the code

To enable typescript support for vscode’s eslint plugin, add the following configuration to.vscode/settings.json.

{
  "eslint.validate": [
    "javascript"."javascriptreact",
    { "language": "typescript"."autoFix": true },
    { "language": "typescriptreact"."autoFix": true}}]Copy the code

integrationprettier

Prettier is an opinionated code formatter

Opinionated Prettier provides little configuration and forces an agreed code style.

Prettier formatting our code prettier formatting our code prettier formatting our code prettier formatting is recommended when Git commit, to set hooks for Git, use the Husky tool.

yarn add -D husky lint-staged prettier
Copy the code

Lint-staged is a tool for speeding up Lint tools. Just as its name suggests, Lint-staged tools can speed Up Lint by having only code stored in stages.

Next, configure HusKY and Lint-staged. Add the following to package.json.

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
      "prettier --single-quote --write",
      "git add"
    ]
  },
Copy the code

If prettier also needs to be configured, add the.prettierrc.js configuration file in the root directory of the project. As mentioned earlier, Prettier has few configuration options. As follows:

// prettier.config.js or .prettierrc.js
module.exports = {
    trailingComma: "es5",
    tabWidth: 4,
    semi: false,
    singleQuote: true
};
Copy the code

integrationstylelint

For the Stylelint I mainly refer to the Ant Design configuration.

yarn add -D stylelint
Copy the code

Add the stylelint configuration file.stylelintrc.json or package to the root directory and add the field “stylelint” as follows:

{
  "extends": [
    "stylelint-config-standard"."stylelint-config-rational-order"."stylelint-config-prettier"]."plugins": ["stylelint-order"."stylelint-declaration-block-no-ignored-properties"]."rules": {
    "comment-empty-line-before": null."function-name-case": ["lower"]."no-invalid-double-slash-comments": null."no-descending-specificity": null."declaration-empty-line-before": null
  },
    "ignoreFiles": []}Copy the code

Install the plug-in used in the above configuration.

yarn add -D stylelint-config-standard stylelint-config-rational-order stylelint-config-prettier stylelint-order stylelint-declaration-block-no-ignored-properties
Copy the code

Modify lint-staged configuration to:

"lint-staged": {
    "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
      "prettier --single-quote --write",
      "git add"
    ],
    "src/**/*.css": "stylelint",
    "src/**/*.scss": "stylelint --syntax=scss"
},
Copy the code

Configuration commitlint

Recommend a tool that implements specification submission instructions: Commitizen/CZ – CLI. Install the tool globally:

yarn global add commitizen
Copy the code

The tool can be used in a GIF of the submitted code at the end of the article. To use it, enter git cz.

Install the verification tool @commitlint/ CLI.

yarn add -D @commitlint/cli
Copy the code

Install Angular style validation rules.

yarn add -D @commitlint/config-conventional 
Copy the code

Package. json add the “commitlint” field and set:

"commitlint": {
    "extends": [
      "@commitlint/config-conventional"
    ]
}
Copy the code

Change the husky configuration in package.json to:

"husky": {
        "hooks": {
            "pre-commit": "lint-staged",
            "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
        }
},
Copy the code

Adjust the template

I wrote this article while configuring one of my projects. Some of the content below is configured according to the technology stack of my project, and the rest is configured according to my own needs. For example, if I want to write a project using React hooks, install the react-use library. If I don’t want to use React hooks, don’t install it.

Adding common Folders

Add the docs folder to the project root directory for your documents. Add assets, Components, Pages, Stores, Models (typescript classes or interfaces), utils, Styles these folders. Add index.tsx to the images, videos, etc. Components and Pages directories to export all components and pages.

Delete unnecessary files and content

Public /manifest.json is used to make PWA. Modify the home page title in public/index.html. The contents of app.scss can be deleted completely. SRC /logo.svg can be deleted. Remove useless code from app.tsx. The default readme. md generated by CRA was also stripped out and added with its own project description.

Replace the website icon favicon.ico

You are advised to use iconFX to create ICONS in ICO format. Iconfx is easy to use, just open the software and use it. Images can be directly converted into ICO ICONS. Replace public/favicon.ico with the created icon to set up the site icon.

Add other dependencies

Install react-router-dom, classnames, Lodash, react-use, constate, faker.js, and the corresponding types file. Things like React-use and constate are written in typescript so you don’t need to install the corresponding types. Install normalize.css and import it directly from index.tsx.

At this point, the development environment for my project is configured and ready for business development.

One of my projects that is configured exactly according to the above steps is mini-shop. If you need it, you can go directly to my configuration. Generally speaking, the configuration will not be changed often.

Take a look at what submission code looks like with the above tools configured:

This article is original content, first published in personal blog, reproduced please indicate the source.

References:

  1. Create-react-app Official document
  2. Use Ant Design in create-React-app
  3. Git commit specification

This article is original content, first published in personal blog, reproduced please indicate the source.