Create a React project

Companies typically build their own projects without official scaffolding

create-react-app

NPX create-react-app my-app or NPM init react-app my-app or yarn create react-app NPX create-react-app my-app --typescript, I'm using the former here, adding ts manuallyCopy the code

(2) Introducing TS

Yarn add typescript # add tsconfig.json! Then change the JS file to TSX, restart the project, and add the TS declaration file module @types to the existing module as neededCopy the code

Tsconfig. ts tsconfig.json If there is a tsconfig.json file in a directory, this directory is the root of the TS project. Tsconfig. json specifies the root file and compilation options to compile this project. This file is shared by IED, TSC and TS-Loader

Using tsconfig. Json

The ts compile configuration file specifies which files to compile, which types of files to compile, which types of files to generate, and so on. The # tsconfig.json file can be empty, and all default files (as described above) will be compiled with the default configuration options. # compilerOptions {"target": "ES5", // target language version "module": "commonjs", // specify template standard "noImplicitAny" to generate code: True, // Implicitly disallowing any type "removeComments": true, // removing the annotation "preserveConstEnums": true, // Preserving const and enum declarations "sourceMap": True // Generate destination file sourceMap file "incremental": TsBuildInfoFile: tsBuildInfoFile: tsBuildInfoFile: tsBuildInfoFile: tsBuildInfoFile: "./buildFile", // Store the incremental compiled file "diagnostics": true, // Print the diagnostic information "outFile": "./app.js", // Generate a file from multiple interdependent files, which can be used in AMD modules, i.e. "module": "AMD", "lib": ["DOM", "ES2015", "ScriptHost", "es209.array "], // The library that TS needs to reference, that is, the declaration file, ES5 default reference DOM, ES5, ScriptHost, if you need to use es advanced version features, usually need to configure. Array", "allowJS": true, // allows the compiler to compile JS, JSX file "checkJs": True, // Allow errors in JS files, usually with allowJS using "outDir": "./dist", // specify output directory "rootDir": "./", // Specify the output directory (for output), which controls the structure of the output directory "declaration": true, "./file", // Specify "emitationonly ": true, // only declaration file will be generated, not js file" inlineSourceMap": Inline SourceMap is included in the generated JS file "declarationMap": true, // The SourceMap "typeRoots" is generated for the declaration file: Node_modules /@types "types": []; // noEmit: true; // noEmitOnError: "NoEmitHelpers ": true, "noEmitHelpers": true, "noEmitHelpers": true, "noEmitHelpers": true, "noEmitHelpers": true, "noEmitHelpers": true, "noEmitHelpers": true True, // Introduce a helper function via tslib, the file must be the module "downlevelIteration": true, // The degraded traverser implementation, if the target source is ES3/5, then the traverser has the degraded implementation "strict": True, // enable all strict type checks "alwaysStrict": true, // inject 'use strict' "strictNullChecks" into the code: True, / / do not allow the null, and undefined assigned to other types of variables "strictFunctionTypes" : true, / / do not allow two-way covariance function parameters "strictPropertyInitialization" : True, // Class instance attributes must be initialized with "strictBindCallApply": true, // strict bind/call/apply check "noImplicitThis": NoUnusedParameters can be set to noUnusedParameters (), // Can be set to noUnusedParameters (). True, / / check unused function parameters (tip is not only an error) "noFallthroughCasesInSwitch" : "NoImplicitReturns ": true, // Each branch will return the value "esModuleInterop": True, // Allow export= export, import from import "allowUmdGlobalAccess": true, // allow global access to the umD module "moduleResolution": "Node ", // the default path for modules is "baseUrl": "./", // The default path for non-relative modules is "paths": {// Path mapping, relative to baseUrl // If you do not want to use the default jQ version and need to specify the version manually, you can configure "jquery" as follows: ["node_modules/jquery/dist/jquery.min.js"] }, "rootDirs": [" SRC ","out"], // Put multiple directories in a virtual directory, which can be used at runtime, i.e. the location of imported files may change after compilation. This can also be set to the same directory SRC and out, no need to change the path and no error "listEmittedFiles": }, "files": [// specify the file to be compiled "./ SRC /index.ts"], "compileOnSave": False, // Set the editor to automatically compile "exclude" when saving the file: [// specify the files or folders that the compiler needs to exclude. By default, files in the node_modules folder are excluded. "SRC /lib" // exclude files in the SRC lib folder from compiling. By default, all TypeScript files in the current directory and subdirectories are included. "Extends ": "./tsconfig.base.json" extends": "./tsconfig.base.json"// extracts the base configuration into a tsconfig.base.json file and then introduces // specifies a list of individual files to compile "files": [// specify leo.ts file in SRC directory "SCR /leo.ts"] // specify file or directory "include" to compile: [// "SCR" // will compile all files under SRC, including subdirectories // "SCR /*" // will compile only files under SCR level 1 directory" SCR /*/*" // will compile only files under SCR level 2 directory] // Specifies project reference dependencies. In the project development, sometimes we in order to facilitate the front-end project and back-end node project in the same directory development, two projects rely on the same configuration file and general file, but we hope to be flexible before and after the project package respectively "References ": [// specify dependent project {"path": "./common"}] // Set auto-import library type definition file (.d.ts) correlation. Contains three subattributes: enable: Indicates whether to enable automatic import of library type definition files (.d.ts). The default value is false. Include: array type, library names that allow automatic introduction, e.g. [" jquery ", "lodash"]; Exculde: Array type, the name of the excluded library. "typeAcquisition": { "enable": false, "exclude": ["jquery"], "include": ["jest"] } }Copy the code

When you call TSC without any input files, the compiler looks for the tsconfig.json file starting in the current directory and working its way up the parent directory. Use the command line argument –project (or -p) to specify a directory containing the tsconfig.json file.

The tsconfig.json file is ignored when an input file is specified on the command line.

(3) Webpack.config. js configuration in the project

Create-react-app uses babel-Loader to handle TypeScript code, where ts-Loader is added to rules and the internal source code of TS-Loader calls the TS compiler (TSC).

const path = require('path'); module.exports = { entry: './src/index.ts', devtool: 'inline-source-map',// To enable Source map, we must configure TypeScript to output the inline Source map to the compiled JavaScript file. Module: {rules: [{test: /\.tsx?$/, use: {rules: [{test: /\.tsx? [{loader: 'ts-loader', option: {// if enabled, the compiler will only convert language and will not check type, and will not prevent transpileOnly: false}}], exclude: /node_modules/ } ] }, resolve: { extensions: [ '.tsx', '.ts', '.js' ] }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } };Copy the code

eslint

Eslint-config-react-app supports es code checking, but has ts code checking but is not enabled. You need to configure this in vscode to support ts code checking

Create a new folder in the vscode setting project. Vscode /setting.json

{
"eslint.validate": [
  "javascript",
  "javascriptreact"
]
}
Copy the code

Eslint NPM package

For code checking, webpack use, is a loader to check the rules of some files while compiling, if there is an error console at compile time, or pause the compilation

npm install eslint --save-dev
eslint --init
Copy the code

Json file, and esLint reads the rule compilation file from this file

{"env":{"browser":true,// node environment "ES6 ":true,// ES6 syntax "commonjs":true,//commonjs "Worker ":true//webwork syntax}, "globals":{"Atomics":"readonly", "SharedArrayBuffer":"readonly"}, // Parser can be configured, The default is to use typescript parsers, "parser": "@typescript-eslint/parser ", "rules": {"semi": ["error", "always"], "quotes": ["error", "single"], "no-console":1}, // It provides inheritance functionality that directly integrates some default configurations. "extends":[" esLint :recommended", "Plugin :@typescript-eslint/eslint-recommended"], // add a variety of plugins, e.g., what if you want to add React checks? Install the eslint-plugin-react plugin and add the following "plugins" to the configuration :["react "]}Copy the code

Description of the configuration file If you perform the preceding operations, the default.eslintrc.js configuration file is generated. The content is as follows:

// .eslintrc.js 
module.exports = {
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true
        },
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "indent": [
            "error",
            "tab"
        ],
        "linebreak-style": [
            "error",
            "windows"
        ],
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "error",
            "always"
        ]
    }
}
Copy the code

This file exports an object containing the env, extends, parserOptions, plugins, and Rules attributes. As beginners to Eslint, we want to learn as much as we can about what each attribute is and what it does, just to get a little bit of security.

Env, parserOptions, and plugins are all put together because you only need to know what they are: I use ES6, React, and JSX syntax in my application, and these attributes allow Eslint to check these syntax. You don’t need to know any more than that.

The author wasted a lot of time in this section at the beginning of learning. After reading the official document for many times, most of them could not understand its meaning. Later, I thought that since it provides such a tool to automatically generate configuration files and the way of command line interaction, I only need to tell it that I need to use ES6, React and JSX syntax. It will automatically configure it to meet my requirements.

Extends has been talking about checking that code follows a coding specification. What exactly is that?

An extends property with a value of “ESLint :recommended” enables a set of core rules that have been proven as best practices (that is, coding specifications that most people think they should follow). If you want to know what the best practices are, Rule items marked √ can be viewed in the ESLint rule table.

Eslint-config-airbnb is someone else’s custom code specification if you don’t like the default rules provided by Npm. Configure “extends” in our own.eslintrc.js: The prefix “airbnb”, eslint-config can be omitted so that we use the rule in eslint-config-Airbnb instead of the official rule “extends”:”eslint:recommended”. For details about how to create and share custom rule configurations, see: How do I Customize Rule Configurations

A few words about the “Airbnb” coding specification, most authors working with most open source projects use the “Airbnb” coding specification rather than the official “extends”: “ESLint :recommended” coding specification.

If we feel that certain rules in the eslint-config-Airbnb rule configuration do not meet the requirements of the current project, we can directly configure the rules property in.eslintrc.js to take precedence over the shared rule airbnb.

The rules configuration file is also generated, so how do we know what rules our system will follow?

In the previous example, the use of NPM run lint check out the three mistakes, if string of our project is to use single quotes, not double quotes, end code is either a semicolon is good-looking, variable is defined may not use, we can set up rules to define our own code conventions, the rules.

ESLint comes with a large number of rules, which should be modified according to the following requirements:

“Off” or 0 – turn off the rule “WARN” or 1 – turn on the rule, using warning level errors: WARN (will not cause the program to exit) “error” or 2 – turn on the rule, using error level errors: Error (when triggered, the program exits.) Some rules have no attributes and just control whether they are turned on or off, like this: “eqeqeq”: “off”. Some rules have their own attributes and are used like this: “quotes”: [“error”, “double”], check the ESLint rule table for built-in attributes.

Modify the rules property in.eslintrc.js:

"rules": { "indent": [ "error", "tab" ], "linebreak-style": [ "error", "windows" ], "quotes": ["error", "single" // "string" must be enclosed in single quotes instead of double quotes, 'string' does not return an error, "string" returns an error], "semi": ["error", "never" // change the end of the code without a semicolon], "no-unused-vars": 0 // 0 is equivalent to off, indicating that the rule is disabled.Copy the code

NPM Run Lint is used to verify the code. If no error is reported, the verification passes and the code conforms to the unified coding specification.

Eslint vscode plug-in

Vscode: eslint.autoFixOnSave: “eslint.autoFixOnSave”: “eslint.autoFixOnSave”: “eslint.autoFixOnSave”: “eslint.autoFixOnSave”: true,

{// # automatically format "editor.formatOnSave": true, // # fix code in ESLint format every time you save: { "source.fixAll.eslint": true }, "eslint.validate": ["javascript", "javascriptreact"], // VScode by default enables the option "editor.detectIndentation" to automatically set tabsize based on the file type: False, // reset tabsize "editor. tabsize ": 2, / / # let function (name) and add a space between the brackets behind the "javascript. The format. InsertSpaceBeforeFunctionParenthesis" : true, "window. The zoomLevel" : 0, "explorer.confirmDelete": false, "explorer.confirmDragAndDrop": false, "editor.renderControlCharacters": true, "editor.renderWhitespace": "all", "[jsonc]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } }Copy the code

Tslint has stopped maintenance, use ESLint instead

Prettier

Prettier website

A code formatting tool that forces code formatting using Prettier’s rules

Prettier NPM package.prettierrc.json But few people use the command line, use IDE, direct code formatting through IDE and PRtTier integration

mkdir learn-prettier && cd learn-prettier yarn init yarn add prettier --dev --exact // Create an index.js file in the learn-prettier/ SRC directory, then write some JS code yourself. The JS code uses the very long foo(......) You can, you can also change some more messy, but must conform to JS syntax. Yarn prettier --write SRC /index.js // after formatting the index.js file, it has been reprinted into a fixed format. / / a formatted all code yarn prettier - write '. / SRC / / * * *. Js' '. / SRC / / * * *. JSX 'Copy the code

Prettier after vscode plug-in is installed setting.json

/ / prettier use validated code format eslint "prettier. EslintIntegration" : true, "prettier. Semi" : False, # remove semicolon at end of code "prettier.singleQuote": true, # use quotation marks instead of double quotesCopy the code

Prettier reiterates that she is an Opinionated code formatter and has only a few options. This means:

Prettier is not a code-style formatting tool that you can do as you like, not let you change the output of Prettier. The primary purpose is to get the team to stop bickering, and the more configuration items there are, the further away they are from that primary purpose, and the team is always talking about how they should be configured. That’s Prettier’s philosophy

Their integration requires Prettier and Linters to do two things:

Disable Linters’ own Formatting rules and let Prettier take over the duties. These configurations have readily available Config’s that Linters’ configurations can inherit. Allows Linters to perform the formatting first by calling Prettier and then checking the code-quality class rules. This is achieved by Linters’ Plugin.

The VUE project configures the rules and saves the automatic formatting code

1..eslint.js configuration

module.exports = { root: true, parserOptions: { parser: 'babel-eslint', sourceType: 'module' }, env: { browser: True, node: true, es6: true,}, // ['plugin:vue/recommended', 'eslint:recommended'], // add your custom rules here //it is base on https://github.com/vuejs/eslint-config-vue rules: { "vue/max-attributes-per-line": [2, { "singleline": 10, "multiline": { "max": 1, "allowFirstLine": false } }], "vue/singleline-html-element-content-newline": "off", "vue/multiline-html-element-content-newline":"off", "vue/name-property-casing": ["error", "PascalCase"], "vue/no-v-html": "off", 'accessor-pairs': 2, 'arrow-spacing': [2, { 'before': true, 'after': true }], 'block-spacing': [2, 'always'], 'brace-style': [2, '1tbs', { 'allowSingleLine': true }], 'camelcase': [0, { 'properties': 'always' }], 'comma-dangle': [2, 'never'], 'comma-spacing': [2, { 'before': false, 'after': true }], 'comma-style': [2, 'last'], 'constructor-super': 2, 'curly': [2, 'multi-line'], 'dot-location': [2, 'property'], 'eol-last': 2, 'eqeqeq': ["error", "always", {"null": "ignore"}], 'generator-star-spacing': [2, { 'before': true, 'after': true }], 'handle-callback-err': [2, '^(err|error)$'], 'indent': [2, 2, { 'SwitchCase': 1 }], 'jsx-quotes': [2, 'prefer-single'], 'key-spacing': [2, { 'beforeColon': false, 'afterColon': true }], 'keyword-spacing': [2, { 'before': true, 'after': true }], 'new-cap': [2, { 'newIsCap': true, 'capIsNew': false }], 'new-parens': 2, 'no-array-constructor': 2, 'no-caller': 2, 'no-console': 'off', 'no-class-assign': 2, 'no-cond-assign': 2, 'no-const-assign': 2, 'no-control-regex': 0, 'no-delete-var': 2, 'no-dupe-args': 2, 'no-dupe-class-members': 2, 'no-dupe-keys': 2, 'no-duplicate-case': 2, 'no-empty-character-class': 2, 'no-empty-pattern': 2, 'no-eval': 2, 'no-ex-assign': 2, 'no-extend-native': 2, 'no-extra-bind': 2, 'no-extra-boolean-cast': 2, 'no-extra-parens': [2, 'functions'], 'no-fallthrough': 2, 'no-floating-decimal': 2, 'no-func-assign': 2, 'no-implied-eval': 2, 'no-inner-declarations': [2, 'functions'], 'no-invalid-regexp': 2, 'no-irregular-whitespace': 2, 'no-iterator': 2, 'no-label-var': 2, 'no-labels': [2, { 'allowLoop': false, 'allowSwitch': false }], 'no-lone-blocks': 2, 'no-mixed-spaces-and-tabs': 2, 'no-multi-spaces': 2, 'no-multi-str': 2, 'no-multiple-empty-lines': [2, { 'max': 1 }], 'no-native-reassign': 2, 'no-negated-in-lhs': 2, 'no-new-object': 2, 'no-new-require': 2, 'no-new-symbol': 2, 'no-new-wrappers': 2, 'no-obj-calls': 2, 'no-octal': 2, 'no-octal-escape': 2, 'no-path-concat': 2, 'no-proto': 2, 'no-redeclare': 2, 'no-regex-spaces': 2, 'no-return-assign': [2, 'except-parens'], 'no-self-assign': 2, 'no-self-compare': 2, 'no-sequences': 2, 'no-shadow-restricted-names': 2, 'no-spaced-func': 2, 'no-sparse-arrays': 2, 'no-this-before-super': 2, 'no-throw-literal': 2, 'no-trailing-spaces': 2, 'no-undef': 2, 'no-undef-init': 2, 'no-unexpected-multiline': 2, 'no-unmodified-loop-condition': 2, 'no-unneeded-ternary': [2, { 'defaultAssignment': false }], 'no-unreachable': 2, 'no-unsafe-finally': 2, 'no-unused-vars': [2, { 'vars': 'all', 'args': 'none' }], 'no-useless-call': 2, 'no-useless-computed-key': 2, 'no-useless-constructor': 2, 'no-useless-escape': 0, 'no-whitespace-before-property': 2, 'no-with': 2, 'one-var': [2, { 'initialized': 'never' }], 'operator-linebreak': [2, 'after', { 'overrides': { '?': 'before', ':': 'before' } }], 'padded-blocks': [2, 'never'], 'quotes': [2, 'single', { 'avoidEscape': true, 'allowTemplateLiterals': true }], 'semi': [2, 'never'], 'semi-spacing': [2, { 'before': false, 'after': true }], 'space-before-blocks': [2, 'always'], 'space-before-function-paren': [2, 'never'], 'space-in-parens': [2, 'never'], 'space-infix-ops': 2, 'space-unary-ops': [2, { 'words': true, 'nonwords': false }], 'spaced-comment': [2, 'always', { 'markers': ['global', 'globals', 'eslint', 'eslint-disable', '*package', '!', ','] }], 'template-curly-spacing': [2, 'never'], 'use-isnan': 2, 'valid-typeof': 2, 'wrap-iife': [2, 'any'], 'yield-star-spacing': [2, 'both'], 'yoda': [2, 'never'], 'prefer-const': 2, 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0, 'object-curly-spacing': [2, 'always', { objectsInObjects: false }], 'array-bracket-spacing': [2, 'never'] } }Copy the code

Set vscode to setting.json

{// # automatically format "editor.formatOnSave": true, // # fix the code in eslint format every time you save "editor.codeActionsOnSave": {" source.fixall.eslint ": true}, "eslint.format.enable": true, //autoFix is enabled by default, just input the string array "eslint.validate": [" javascript ", "vue", "HTML"], / / # prettier use validated code format eslint "prettier. EslintIntegration" : "SingleQuote ": true, // # prettier.semi: false # prettier.semi: false # prettier.singlequote: True, / / # let function (name) and add a space between the brackets behind the "javascript. The format. InsertSpaceBeforeFunctionParenthesis" : true, "vetur.format.defaultFormatterOptions": { // "js-beautify-html": { // "wrap_attributes": "Force-aligned" // // # HTML code formatting styles in vue components // "prettier": {// prettier option here "trailingComma": "Es5 ", // for multiple lines, print trailing comma "tabWidth": 4, // ignore vetur's tabSize configuration "useTabs": false, // whether to use TAB instead of space "semi": true, // whether to add at the end of the sentence; "SingleQuote ": true, // Use single quotation marks instead of double quotation marks "arrowParens": "avoid", // allow aren-less arrow functions use parentheses}}}Copy the code

www.zuiyu1818.cn/posts/VScod…

Eslint – plugin – eslint.vuejs.org/rules/html- vue web site…

Eslint-plugin-vue on Github under vuejs project github.com/vuejs/eslin…

Automatic formatting

1. Write the configuration in.eslint.json

2, vscode setting to write the configuration

{// # fix the code in ESLint format every time you save it read the esLint rule configuration file "editor.codeActionsOnSave": {" source.fixall.eslint ": true}}Copy the code

3. Enable eslint in the vscode editor

4. Write instructions in package.json if you want to format all the code

"lint-fix": "eslint --fix --ext .js --ext .vue src/biz"
Copy the code

Then run this command to format all js and vue files under SRC /biz

5 Turn off ESLint checking for a piece of code in a single file

Multiple lines:

/* eslint-disable */
window.webkit.messageHandlers.jsCallOC.postMessage({name: 'tttt', age: 18, big: true});
Copy the code
/* eslint-enable */
Copy the code

Single line:

// eslint-disable-next-line
// eslint-disable-line
Copy the code