I wrote a post about how to build a React + typescript + Ant Design development environment, but a lot of it is now out of date. However, I saw that some readers gave me a thumbs-up on this article not long ago. If I don’t update it, I always feel cheated by them and feel a little sorry. However, if I had to configure that environment again now, I would definitely not configure it like that article. After all, a long time has passed, many tools have developed and my thinking has changed, so I would just write a new article, which is one of my motivations for writing this article.

Recently, I have written many types of projects, such as Chrome extension, VSCode extension, electron, etc. The configuration development environment is written naked, without using some CLI tools or third party project templates. Therefore, I stepped on a lot of pits, but also summed up a lot of experience. So another creative motivation was to summarize and share my best practices for configuring development environments.

The developer and editor I use are win10pro-1909 and VSCode respectively. All the dependencies I use are up to date, and the article will be updated from time to time to ensure timeliness.

The article will be divided into four parts in the chronological order of developing a template project:

  1. dotfiles
  2. Linters and the formatter
  3. webpack
  4. Third party library integration and optimization

Project address: React-typescript-boilerplate

init

The first step in setting up your project is to create a new project folder and initialize it as a Git repository:

Create a new project folder
mkdir react-typescript-boilerplate
Switch the working path to the project folder
cd The $_
Initialize git repository
git init
Copy the code

You can replace the react-typescript-boilerplate with whatever project name you want, with $_ representing the argument at the end of the previous command, which represents the project folder.

By “dotfiles” I mean configuration files that start with a dot. When I first started to learn front-end framework, I was also confused when I saw a bunch of dotfiles generated by scaffolding, thinking how to write a project requires so many configuration files, and it is too much trouble to write a front-end project. The fact that they exist makes sense, and once I understand what they are used for, I can understand why they are necessary, and the number of configuration files is in part a reflection of the vibrant front-end build tool ecosystem.

.gitignore

It is recommended that the first step after initializing your Git repository is to add.gitignore. If you don’t, VSCode version control will monitor all the files in your project including a bunch of files under node_modules, leading to high CPU and memory usage, so it’s best to configure gitignore from the start. To configure gitignore, it is recommended to use the gitignore extension of VSCode. It’s easy to use: CTRL + Shift + P brings up the command panel, call Add gitignore, and select ignore configuration for different types of projects. You can append multiple times.

The project types I usually add include: Node, VisualStudioCode, JetBrains, Windows, Linux, macOS, you can add other project types according to your needs like SublimeText, Vim. Although I was developing with VSCode, I added the ignore configuration related to JetBrains IDE in consideration of the fact that someone else might be developing the project using WebStorm. This extension works by pulling the Gitignore configuration from the open source project gitignore. Note that we will remove typings/ and Icon. The typings folder is used to store ts type definition files, and the Icon folder is used to store ICONS.

.editorconfig

By configuring EditorConfig, we can keep the code formatting style consistent across multiple developers using different editors. Some ides such as IDEA come directly with the editorconfig specification, while some editors such as VSCode require plug-ins to support it.

Here is the test file index.js on the left and the editorCofig configuration on the right. Notice that I deliberately set the indentation to 3 Spaces. VSCode can set the formatter it uses to format code. If you don’t set the formatter, you use the built-in formatter.

"[javascript]": {
    "editor.defaultFormatter": "vscode.typescript-language-features"
 }
Copy the code

As you can see after I format Alt + shift + f, VSCode follows editorconfig’s configuration to format the indent to 3 Spaces.

I continued to open the project in IDEA and format it by CTRL + Alt + L. Unsurprisingly, it also formatted into three Spaces, so I did not map it, just like the above. So editorConfig allows us to keep formatting styles consistent across different editors.

Prettier one might wonder why prettier is a formatting tool when prettier is also a formatting tool. In fact, some well-known open source projects like react and VSCode use both. Think about it: Prettier must eventually format code from Lint-staged versions, usually formatting code after it has been modified each time. Does that mean editorConfig is useless?

Where editorConfig and Prettier differ essentially: Editorconfig is active in the editor. You add the.editoronfig file, call VSCode for formatting, and the result is the.editorconfig configuration style. Prettier is just a command-line tool that you need to call to format code; prettier is passive. Prettier if you do not configure EditorConfig, editing a file, calling VSCode to format the code manually, prettier formats the file because VSCode’s built-in formatter does not prettier, As a result, I manually formatted it, but it was modified after I submitted it. Editing EditorConfig in the same style as Prettier solves the problem of formatting things differently than prettier. In fact, that’s what react does.

The editorconfig configuration is useless when prettier is configured as the javascript formatter for VSCode.

It is recommended to install the VSCode extension EditorConfig for VSCode. After installing it, you can Generate the default configuration by using the command generate. editorcofig. I recommend that you add a line end_of_line = unset at the end of the line so that the end newline follows the operating system newline.

root = true

[*]
indent_style = space
indent_size = 4
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = false
Plus this row
end_of_line = unset
Copy the code

.nvmrc

Node Version Manager (NVM) is the node version management tool. To use NVM on Windows, install another tool, NVM-Windows.

NVMRC is an NVM configuration file that many tools, such as Travis CI, will read when determining the node version of the project. There is no need to specify the node version in.travis. Yml if the project root path has.nvmrc. It is recommended to use the latest LTS version for daily development. The new version not only supports more ES features, but also generally has improved performance and fewer bugs. It is not recommended to choose the latest non-LTS version of your project. Some packages such as Bcrypt are not supported in the latest non-LTS version at all. A friend of mine was having trouble installing Bcrypt, and it turned out that bcrypt was only being tested on LTS versions of Node, and there was no guarantee that bcrypt would support non-LTS versions.

Generate.nvmrc with the following shell command:

node --version > ./.nvmrc
Copy the code

.npmrc

As we all know, due to irresistible force, domestic no matter accessing Github or downloading NPM package is snail speed. For domestic users, the first thing we need to do is to set the NPM source to taobao source. NRM is recommended for configuring the NPM source:

# install NRM globally
yarn global add nrm
Or use NPM to install
npm i -g nrm
# Set the use of Taobao source
nrm use taobao
Copy the code

There are other sources we can see from NRM ls:

$ nrm ls

  npm -------- https://registry.npmjs.org/
  yarn ------- https://registry.yarnpkg.com/
  cnpm ------- http://r.cnpmjs.org/
* taobao ----- https://registry.npm.taobao.org/
  nj --------- https://registry.nodejitsu.com/
  npmMirror -- https://skimdb.npmjs.com/registry/
  edunpm ----- http://registry.enpmjs.org/
Copy the code

Test the packet loss rate of a few of these common sources:

NPMRC is the configuration file for NPM. Of course, if you use yarn, yarn also complies with the. NPMRC configuration, although yarn has its own. Yarnrc configuration file.

We know that some NPM packages require some binary dependencies to be downloaded during installation, and some of them, such as Node-Sass, Electron, bcrypt, also need to configure agents to download. To make it easier for others to install them on collaborative projects, we can set their mirror address directly in.npmrc and add the mirror address of Node-sass:

# .npmrc
SASS_BINARY_SITE=http://npm.taobao.org/mirrors/node-sass
Copy the code

We can view more commonly used mirror addresses in Taobao NPM mirror.

LICENSE

Choose a license based on your project type, choose a license, copy the license file, paste it to the license file or license. TXT file in the project root path, and modify some configurations. Here I choose the loose MIT protocol and change the year and author name:

MIT License

Copyright (c) [2020] [YuTengjing]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Copy the code

package.json

One question to consider when generating package.json is: do you plan to use YARN, NPM, or CNPM?

It seems that YARn2 has been released recently, but I will definitely not consider yarn2 at present, not to mention many bugs, it is not mature enough, and the acceptance of the community is still a problem, yarn2 and YARN1 are very different.

NPM is designed to add dependencies to yarn.It is not added to dependencies by default. The design of using cache was created by YARN, and the locking version was copied from YARN.

Yarn is much more comfortable to use. However, yarn often has a bug in Windows that the hash value does not match and then cannot be installed, which makes me very annoyed. I have looked at github repository and found nearly 2000 issues.

Recently, I tried CNPM again. To my surprise, the download speed is really fast. CNPM is much faster than YARN when using taobao source. But I think after CNPM is installed, node_modules looks messy and has a lot of messy dependencies.

Because I’m a bit of a neat freak, SO YARN and CNPM stand yarn. Another killer feature of YARN is that yarn workspace is used to manage monorepos dependencies. Although this project is not a Monorepos structure, it does illustrate a problem that NPM is far behind YARN in engineering.

Package. json is the configuration file used to manage NPM packages. The easiest way to generate package.json is to use yarn init -y to generate a default package.json file.

{
  "name": "react-typescript-boilerplate"."version": "1.0.0"."main": "index.js"."author": "YuTengjing <[email protected]>"."license": "MIT"
}
Copy the code

Let’s change the default configuration:

Since we are not going to publish this project to NPM, set private to true.

The main entry doesn’t make sense for our template project, so we just delete it.

Modify the format of author and repository to look like this:

{
  "name": "react-typescript-boilerplate"."version": "1.0.0"."description": "A boilerplate for react + typescript development"."private": true."author": {
    "name": "YuTengjing"."url": "https://github.com/tjx666"."email": "[email protected]"
  },
  "repository": {
    "type": "git"."url": "[email protected]:tjx666/react-typescript-boilerplate.git"
  },
  "license": "MIT"."scripts": {}}Copy the code

settings.json

If you are using VSCode, you can add the VSCode project configuration file.vscode/settings.json. Create a new.vscode folder and create a settings.json file in it. Json is a jsonC file. The difference between jSONc and JSON files is that jSONc allows you to add comments. Temporarily add the following:

{
    // The stylelint extension itself is sufficient for the checksum
    "css.validate": false."less.validate": false."scss.validate": false.// use locally installed TypeScript instead of VSCode's built-in smarts
    "typescript.tsdk": "./node_modules/typescript/lib".// Specify which files do not participate in the search
    "search.exclude": {
        "**/node_modules": true."dist": true."yarn.lock": true
    },
    // Specify files that are not monitored by VSCode to prevent CPU usage due to too many files being scanned when VSCode is started
    "files.watcherExclude": {
        "**/.git/objects/**": true."**/.git/subtree-cache/**": true."**/node_modules/*/**": true."**/dist/**": true
    },
    // Configure VScode to use prettier formatter
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[javascriptreact]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[typescript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[typescriptreact]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[jsonc]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[html]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[css]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[less]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[scss]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[yaml]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[markdown]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"}}Copy the code

We can also use.vscode/extensions.json to recommend some extensions to the user. When the user opens the project, vscode will prompt the user to install the recommended extensions if they are not installed. You can also check the filter condition in the extension market to show only the recommended extensions.

// https://gist.github.com/tjx666/daa6317cf80ab5f467c50b2693527875
{
    "recommendations": [
        "editorconfig.editorconfig",
        "dbaeumer.vscode-eslint",
        "esbenp.prettier-vscode",
        "stylelint.vscode-stylelint",
        "dsznajder.es7-react-js-snippets",
        "mrmlnc.vscode-scss",
        "yutengjing.view-github-repository",
        "yutengjing.open-in-external-app"
    ]
}
Copy the code

.travis.yml

I chose to use Travis CI, the most popular open source CI tool. After creating a new repository on Github, I could go to Travis CI’s official website, first synchronize the Github account information, and then search and activate the new repository. I might consider replacing github Actions with Travis for now.

Create a new.travis. Yml file in the project root directory and add the following:

language: node_js
cache:
  - yarn
install:
  - yarn
script:
  - yarn test
Copy the code

Very simple configuration, just responsible for automated testing. Since there are no tests yet, we add an echo statement to NPM scripts:

// package.json
"scripts": {
    "test": "echo 'skip test... '"
}
Copy the code

README.md

The readme. md is the project specification, and the readme. md in each folder is rendered to the page on Github. The readme.md we added to the project root will naturally be rendered to the home page of the repository.

Add some useful badges, such as the build status of Travis CI, whether the Dependencies version is expired, and so on. A badge is essentially a link, but the text part is replaced by an IMAGE rendered in SVG. You can find a variety of badges on shield. IO.

Add the following:

<div align="center">

# react-typescript-boilerplate

[! [Build Status] (https://travis-ci.org/tjx666/react-typescript-boilerplate.svg?branch=master(a)]https://travis-ci.org/tjx666/react-typescript-boilerplate) [! [dependencies Status] (https://david-dm.org/tjx666/react-typescript-boilerplate/status.svg(a)]https://david-dm.org/tjx666/react-typescript-boilerplate) [! [devDependencies Status] (https://david-dm.org/tjx666/react-typescript-boilerplate/dev-status.svg(a)]https://david-dm.org/tjx666/react-typescript-boilerplate?type=dev) [! [Known Vulnerabilities] (https://snyk.io/test/github/tjx666/react-typescript-boilerplate/badge.svg?targetFile=package.json(a)]https://snyk.io/test/github/tjx666/react-typescript-boilerplate?targetFile=package.json) [! [Percentage of issues still open] (https://isitmaintained.com/badge/open/tjx666/react-typescript-boilerplate.svg(a)]http://isitmaintained.com/project/tjx666/react-typescript-boilerplate')

A boilerplate for react + typescript development

</div>
Copy the code

Use the div’s align attribute to center the title, badge, and description.

first commit

At this point I feel ready to commit for the first time:

Add remote repository address
git remote add github [email protected]:tjx666/react-typescript-boilerplate.git
Add all changes to the staging area
git add -A
# submit using :tada: Emoji
git commit -m ":tada: first commit, add some dotfiles"
Git push = git push = git push = git push = git push = git push = git push = git push
git push github -u master
Copy the code

Git emoji generation is recommended using gitmoji-cli or directly using VSCode to extend gitmoji Commit.

The next article continues with configurations of Linters and Formatter.

For more details, we recommend looking directly at the source code at the react-typescript-Boilerplate project. If you find this article useful to you, you can appreciate star 😁. If you have any questions or improvements to this article, please feel free to contact github Issues and the comments section of the platform.

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