preface
Front-end engineering flow configuration is a skill that front-end engineers must master if they want to take charge. This article describes in detail what specifications are involved, how to use them, how to configure them, and the problems encountered if a project is built from scratch. Summary is not easy, feel helpful can be liked, collection. To facilitate the following, I use create-react-app to create a project called jjson -react-template.
The create-React-app does git init for you when you create your project. You can also add this feature when writing your own scaffolding
eslint
Speaking of workflows, ESLint is a plugin for checking JS/TS code specifications. Eslint can help you write more elegant code, but many people run into problems when using ESLint. The biggest problem is that ESLint does not work. Let’s take a look at how to do this.
The introduction of eslint
There are three things we need to do here
1: The editor (mine is VS Code) needs to install the ESLint plugin
2: installs the ESLint package
3: Import the. Eslintrc file
The first two steps are relatively simple, normal operation, the following main talk about. Eslintrc. In many cases, it’s impossible to remember so many rules, so we basically copied them from the Internet. But sometimes it may take some time to copy from the Internet, mainly because there are too many articles on the Internet, and it is easy to disturb us when we choose. And here IN a way that I think is quite elegant, on our Github, there is a Git gists. This is a github feature that allows us to keep snippet of code so that we can find one in advance. The eslintrc configuration is placed on it for easy search (so that you can copy directly to Gist in the future). So, I’ve copied the.eslintrc that I saved before into my project.
Will not commence eslint
With this configuration in place, now let’s talk about situations where ESLint does not take effect. What should we do in this case? Usually three steps.
1: Check that VS Code has the ESLint plugin installed
2: Check whether the ESlintrc rule is correct or whether related plug-ins are installed
3: Restart the editor
Step 1 and Step 3 are easy to skip, but let’s move on to Step 2. Basically, many esLint failures are caused by Step 2. Because we copied the rules, some plugins may not have been installed or the rules may have changed due to the version of ESLint (the rule you find online is a lower version of ESLint, but your current project is a higher version). In the case of my previous project, my VS Code checks are now invalid.
How do you check the second step? Simply run ESLint and ask him to check any file, which will expose the problem. To illustrate this with a partial installation, execute the following command.
./node_modules/eslint/bin/eslint.js ./src/App.js
We can see the error that ‘Airbnb-base’ was not found. In fact, the corresponding plugin is eslint-config-Airbnb-base, so the problem here is that the plugin is not installed. I install first, continue to execute the above command, and error as follows.
Continue to report errors show allowAfterThis this command is not legitimate, illustrate the eslint rules, in high version of writing has changed, I’ll direct comment out the rules and to follow the orders.We find that ESLint has already taken effect, vs Code starts showing errors, and we just have to follow the rules to change them.
.eslintignore
Now let’s talk about. Eslintignore, this is the one I think we need. Because when packaging can reduce the packaging speed, the specific can see I wrote before this front-end optimization detailed and need to pay attention to a few issues. Eslintignore is one thing to be aware of, and one of the reasons why it doesn’t work for a lot of people. The.eslintignore path prefix is/or not written, but do not write./ as follows.
// .eslintignore
./src/__test__/ *. Js error writing / / / / correct term/SRC / __test__ / *. Js or SRC / __test__ / *. JsCopy the code
.stylelintrc/.stylelintignore
We’ll just skip over these two, but they’re almost identical to eslint. If stylelint fails, refer to the ESLint method to fix the problem.
tslint
Tslint is a plugin for checking TS syntax, but since TSLint is no longer officially maintained and ESLint is recommended for checking TS/TSX files, esLint will be used in the future. So how do you do that? Simple, just install some plugins that can check ts. Eslintrc configures (checks ts version) a copy rule, and if it is invalid, just do what ESLintrc did above.
tsconfig.json
For the said tsconfig. Json, its configuration has a lot of, can see the specific website www.tslang.cn/docs/handbo… Let’s take a look at a few of the attributes used in the project.
- module
Description: This field indicates that ts compiled module is what kind of module system, basically has the following several ‘commonjs’ |’ amd ‘|’ system ‘|’ umd ‘|’ es6 ‘|’ es2015 ‘|’ esnext ‘, we use the commonjs/es6, for example, The source code is as follows
export const test = (value: number) = > {
console.log(value);
};
Copy the code
// Commonjs is compiled as follows
"use strict";
Object.defineProperty(exports."__esModule", { value: true });
exports.test = void 0;
const test = (value) = > {
console.log(value);
};
exports.test = test;
Copy the code
// Es6 is compiled as follows
export const test = (value) = > {
console.log(value);
};
Copy the code
- target
Description: This field indicates which object code to compile ts to, es5, ES6, or ESNEXT. This is a field that you should use a lot and I won’t show you.
- lib
This field indicates what libraries need to be imported. By default, the lib field is used to import the DOM library. In plain English, you can use global dom variables like document, and if you write lib but don’t rely on dom, you’ll get an error when you use document, as follows.
- allowJs/checkJs
AllowJs specifies whether to allowJs files in ts files, and checkJs specifies whether to check for js errors.
- jsx
JSX files are compiled in one of three formats: ‘preserve’, ‘react-native’, or ‘react’. In the React project, just set it to react.
- noImplicitAny
Note: This indicates whether a variable is thrown incorrectly when it is of implicit any type. Note that this is implicit, not when you set it to any. I don’t know. Just look at the picture.
- moduleResolution
Description: rules of the said ts in which to introduce file, there are two patterns’ node ‘|’ classic ‘, generally choose node patterns, specific rules about this link.
- include/exclude
For example, if we want to compile all ts/ TSX files under SRC but do not want to compile test files, we can configure the following:
{
"include": [
"src/**/*.ts"."src/**/*.tsx"]."exclude": [
"src/**/*.test.tsx"]}Copy the code
- sourceMap
Generate the corresponding.map file for debugging
- rootDir
The directory where the compiled files are stored
- declaration
The corresponding ‘.d.ts’ file is automatically generated
There are a lot of fields are not a list, we often use a tsConfig configuration, there are detailed comments oh!
The problem
[Bug Mc-10864] – projects created with creative-react-app will not find ‘./logo.svg’ even if the above tsconfig configuration is used. The main reason is that TS does not recognize such modules, so we need to define the module ourselves. The format is as follows.
declare module '*.svg';
Copy the code
Note that this code is written to.d.ts files. So how do you make d.TS work? Roughly as follows, we can in the tsconfig. Json directory types folder at the same level, build a called index. In the folder which s file is written to the above code,. Which s is also a ts file, so also need to compile it, at this point you can use the include fields, as follows
"include": [
"src/**/*.ts"."src/**/*.tsx"."types"].Copy the code
commitlint
Commitlint was previously less focused, but as you get older, more and more projects have a commit specification, so it’s important to know about it. I think there are two main types of commit information. One is the Angular standard specification, which is suitable for the development of xx libraries and XX plug-ins to facilitate the generation of Changelog.md. The other is to write your own submission specifications and apply them to your company’s projects. The following two specifications are described one by one.
Angular Submission Specification
Commitlint (or standard) checks are required after the Angular specification commits, whether standard or non-standard. There is a dedicated plug-in (commitLint) that does the commit work. We can follow the setup. @commitLint/config-Conventional and @commitlint/ CLI plugins are required to be installed. This is where husky comes in. The Husky plugin takes over git hooks and fixes them correctly at the appropriate stage. The configuration in package.json is as follows
"husky": {
"hooks": {
"commint-msg": "commitlint -E HUSKY_GIT_PARAMS"}}Copy the code
confusion
1: Husky must be an earlier version, mine is 4.3.8. But by the time I tried it, Husky was already at version 7.x, and I found that CommTLint wasn’t working, so if you want this configuration to work, you can download 4.3.8 like I did. What if you need a higher version? Hold on a second. We’ll talk about that next.
2: See the configuration above you may be confused, what does -e mean, other letters ok? Don’t panic. In the future, we don’t want to think that this must be a plugin parameter, so just execute –help and you can see the contents, as follows-e: check message in the file at path given by environment variable value HUSKY_GIT_PARAMS can then tell husky which hooks path to check.
3: We keep saying commintLint, but why is @commitlint/ CLI installed? Commitlint /cli is the alias of commitlint. Install @commitlint/cli.
4: Why install @commitlint/ config-Conventional? Commintlint only checks the specification, but you need to define which specification to use. Eslint is a tool for checking specifications, but we’re going to inherit airbnb. Let’s just use @commitlint/ config-Conventional as Airbnb.
5: If you lower the husky version, you’ll get an error because you didn’t specify commitlint.config.js. To tell commitLint which specification to inherit, the configuration is as follows
module.exports = {
extends: [
'@commitlint/config-conventional']};Copy the code
6: Now when the code is submitted, you can see the error, as follows
Angular specification writing
The above set of configurations will allow you to commit code to the correct specification when you commit it. How can that be a correct specification, there are many articles on the Internet, here I do not say too complex, said too complex but let people do not understand, specific can see the official website link. The rough specification is as follows.
<type>(<scope>): <subject>
/ / an empty line
<body>
/ / an empty line
<footer>
Copy the code
1. The most important parts of header are type,scope and subject
Type: build | ci | computer | feat | fix | perf | refactor | test
Scope: specifies the scope of the file to be changed.
Subject: A specific description of the change, such as what bugs were changed or what requirements were added.
!!!!!!!!! Note: The important thing to note here is “feat(package.json): added commintLint functionality “. There must be a space after the colon.
2: The body section is to write a more detailed description, this is optional.
3: The footer section indicates that if your change is destructive, for example, if you are writing a plugin, a major update will change the API. Detailed descriptions are required here including migration instructions.
commitizen/cz-conventional-changelog
If you can’t remember how angular writes, you can install two plugins that automatically organize the commit information when you commit your code. You don’t have to think about it, but I think it’s faster to write it by hand. Cz-conventional – Changelog, like Airbnb, is used in conjunction with Commitizen.
1: Both of them also have a config file, but we wrote it in package.json, as follows
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"}}Copy the code
2: The second problem is that we can’t use Git cz globally because we are locally installed. You can write a script to solve this problem, and instead of saying git commit, you say NPM run commit, which might feel a little rough. The following
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"commit": "git-cz"
},
Copy the code
At this point a submission specification that conforms to the Angular standard is configured.
Our own CommMIT standard
But what if we don’t want to use the Angular specification? One might say that you can set your own commintLint.config.js. It can be, but I always feel that it is within its limits. I want to get the submission information by myself, and then judge by regular rules or other rules according to the submission information, so as to give the corresponding specification, ok? Of course it can. Suppose now we make a product called XX Mall and the project is called json-shopping. Bugs and requirements in this project have a number, so the submission specification we want is “[json-shopping-123]: XXbug fixed “. This specification does not meet the unified error. So what do we do? Let’s refer to vUE’s practices as follows.
1: configure commit-msg as your own script
"hooks": {
"commit-msg": "node scripts/verify-commit-msg.js"
}
Copy the code
2: Create the scripts folder and write verify-commit- MSG
const chalk = require('chalk');
const msgPath = process.env.HUSKY_GIT_PARAMS || '.git/COMMIT_EDITMSG'; // Note that HUSKY_GIT_PARAMS is used because husky is used
const msg = require('fs').readFileSync(msgPath, 'utf-8').trim();
const commitRE = / ^ \ [json - shopping - \ d + \] \ : \ s. 50 {1} /;
if(! commitRE.test(msg)) {console.log();
console.error(
chalk.red('The submitted information does not meet the project requirements as follows \n') +
chalk.red('[json-shopping-xxx]: fix xxxbug\n') +
chalk.red(` or \ n `) +
chalk.red('[json-shopping-xxx]: complete the XXX requirement \n')
)
process.exit(1)}Copy the code
The results are shown as follows
husky
At this point, I don’t want to bother, but the Husky 4.x version is actually enough. However, the version upgrade is too much, in line with the principle of writing to impress yourself, we continue to talk about the husky high version. Husky aside, hooks can do a lot of things for us. Common hooks are pre-commit, commint-msg, pre-push. You can check out this article if you want to know more about hooks. So without further ado, I’m going to upgrade Husky. emmmmmmmm… Commitlint failed after upgrade.
Generate the husky.
The higher version of Husky will require you to use the.husky hooks script, which will not be called in the.git hooks script itself, generating.husky hooks script is very simple. Run the husky install command. However, since husky is locally installed, it is common to write a script command and then run NPM run prepare as follows.
"scripts": {
"start": "react-scripts start"."build": "react-scripts build"."test": "react-scripts test"."eject": "react-scripts eject"."prepare": "husky install"
},
Copy the code
Now generate an hooks script from the husky website and run “NPX husky add. husky/pre-commit” NPM test””. Take a look at the screenshotsWe find that the pre-commit file is generated and begins with a “.”
0 “) _ / husky. Sh “.” Note that when we define the hooks script, we need to include this line at the beginning. What does the husky.sh file under the _ folder doThis article.
Implement commitlint
Now that we know that the higher version of Husky requires a script to be written in the.husky folder, I write the following commit- MSG script as shown in the above example.
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
commitlint -E HUSKY_GIT_PARAMS
Copy the code
1: After git commit, it does not take effect because the script is not executable. Run chmod ug+ x. husky/* to add execution permission to the script.
Commitlint is not global and HUSKY_GIT_PARAMS is no longer written. It needs to be replaced with $1. So it ends up looking like this.
#!/bin/sh
. "$(dirname "$0")/_/husky. npx commitlint -e $1Copy the code
3: If you want to use your own commit specification, write it as follows
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
node ./scripts/verify-commit-msg.js
Copy the code
lint-stage
In front end engineering, I think there are four aspects of inspection
1: Vs Code editor check
2: WebPack compilation check
3: Git commit check
4: CI/CD deployment check
Only by checking these four aspects, I think it is more complete. Today we will introduce VS Code and Git Commit. “Pre-commit: eslint SRC /*.js” checks all files, which is a waste of performance. So lint-Staged came out, and it just checked our submitted files, and it improved performance a lot, so how do you do that? The following
Configuring HUSky (version 7)
.husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
Copy the code
Configuration. Lintstagedrc
{
"*.js": [
"eslint --fix"
],
"*.(css|less)": [
"stylelint --fix"
]
}
Copy the code
Lint-staged plug-ins are always installed, of course.
jest.config.js
A complete project jEST is essential, and the typical steps to configure JEST are as follows: Let’s use the React framework as an example.
Install the jest enzyme @testing-library/ React-hooks plugin
2: Configure jest.config.js as follows
module.exports = {
roots: ['<rootDir>/src'].setupFiles: [].clearMocks: true.collectCoverage: true.transform: {
'^.+\\.tsx? $': 'ts-jest'
},
Jest: a transform must export a 'process' or 'processAsync' function.
moduleNameMapper: {
'^.+\\.(css|less)$': './jest/style.transform.js'
},
transformIgnorePatterns: ['\\\\node_modules\\\\'].globals: {
'ts-jest': {
tsConfig: './tsconfig.json'}},testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx? $'.moduleFileExtensions: ['ts'.'tsx'.'js'.'jsx'.'json'.'node']};Copy the code
3: Error message “A transform must export a process or processAsync function.” may be displayed according to the preceding configuration. The solution is as follows: Create a jest folder and create style.transform.js below that folder with the following content
module.export = {
process() {
return ' '; }};Copy the code
To run a test case, you can simply write a script command and execute it, but here’s what we recommend. Our project is running the test case before committing, so what should we do? Take the husky high version as an example. Create a pre-push script under the.husky folder and add execute permissions as follows
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run test
Copy the code
Then write a script command
"scripts": {
"test": "jest"
},
Copy the code
prettier
“While esLint usually uses prettier for formatting code,” an “eslint” usually uses prettier for formatting code. “While ESlint usually uses prettier for formatting code,” an “ESlint” usually uses prettier for formatting code, “an” ESlint “usually uses prettier for formatting code. For obsessive-compulsive disorder, from baidu search copy a code over, looking at a lot of warnings not handled in time a little unbearable. If prettier is added, the prettier can be automatically formatted when saving. So how do you do that? The following
1: Installs the VS Code plug-in prettier
2: Installs the prettier dependency package
3: configuration prettierrc
{
"trailingComma": "es5",
"tabWidth": 4,
"semi": true,
"singleQuote": true,
"bracketSpacing": false,
"arrowParens": "avoid"
}
Copy the code
4: Set it in vs Code’s Setting and automatically format it after saving
conventional-changelog
This is the last configuration and is primarily used with the Angular specification to generate Changelog.md. First install the Conventional – Changelog-CLI dependency package, and then add a script command as follows
"scripts": {
"changelog": "conventional-changelog-cli -p angular -i CHANGELOG.md -s -r 0"
},
Copy the code
The last
Why do I write this article? First, I want to consolidate my knowledge and make myself capable of building a complete project from zero. Although this is only the first step of specification, it is important. The second reason is that I can reserve a React template so that the next time I come across a React project, I can go to my Github and clone it and use it quickly. The template has been uploaded, you can fork, find problems in the actual project use, and make comments, and end this article with a renderings.
Refer to the article
Husky6 + CommitLint use and script analysis (Husky V4 + V6)