DevUI is a team with both design and engineering perspectives, serving huawei DevCloud platform and huawei internal background systems, as well as designers and front-end engineers. Add devui Helper (Devui-Official) DevUIHelper plugin: Devuihelper-lsp (welcome Star)

The introduction

Use static inspection tools to standardize your project code so that all team members maintain a consistent coding style so that they can focus on core features and improve overall development efficiency.

Here’s a look at the various Lint tools used by the DevUI component library and how to do uniform formatting checking and fixing during code submission.

By reading this guide, hopefully you can also use these Lint tools to “arm” your own projects.

The DevUI component library Lint consistency is ensured using the following tools:

  • prettier
  • tslint
  • stylelint
  • commitlint

To start, you can create each Lint configuration file in the project directory:

/ YourProject ├ ─ ─... ├ ─ ─. Prettierrc ├ ─ ─ tslint. Json ├ ─ ─ the stylelintrc. Json ├ ─ ─ the vscode | ├ ─ ─ extensions. The json | └ ─ ─ Settings. The json └ ─ ─ commitlint.config.jsCopy the code

1 Basic file Format – Prettier

Prettier means “pretty, clever” and the name of a popular code formatting tool that parses code and reprints it using rules you choose to Prettier.

Prettier has the following advantages:

  1. Can be configured to change
  2. Support for multiple languages
  3. Integrate most editors
  4. Concise configuration items

When Prettier is used, code review does not need to talk about code styles, saving time and effort.

Install the prettier:

npm i -D prettier
Copy the code

Example Configure the. Prettierrc file.

Prettier Configuration Reference

// Comments are for the corresponding rule comments, copied to the project can be deleted
{
  "tabWidth": 2.// Set each indentation to 2 Spaces
  "semi": true.// Add a semicolon to the end of the statement
  "singleQuote": true.// Use single quotes
  "jsxSingleQuote": true."bracketSpacing": true.// Print Spaces between parentheses
  "jsxBracketSameLine": true.// Place multiple lines '>' at the end of the last line instead of on another line
  "printWidth":140.// Lines over 140 will break
  "endOfLine": "auto"."proseWrap": "preserve"."trailingComma": "es5"."useTabs": false
}
Copy the code

2 TS format constraint – TSLint

TSLint is an open source TypeScript code style checker that helps developers with readability, maintainability, code correctness, and more. TSLint is widely used in a variety of front-end build tools and editors.

When writing code, the compiler will throw highlights based on TSLint. At compile time, compilation tools can run TSLint and throw errors to stop compilation from continuing, preventing nonconforming code from entering production.

Install tslint:

npm i -D tslint codelyzer
Copy the code

Configure the tslint.json file.

Tslint configuration reference

{
  "rulesDirectory": [
    "node_modules/codelyzer"]."rules": {
    "arrow-return-shorthand": true.// Convert ()=>{return x} to ()=>x
    "callable-types": true.// Interface or literal types with only invocation signatures can be written as function types
    "class-name": true.// Enforce the PascalCased class and interface name
    "comment-format": [
      true."check-space"].Single-line comments must be preceded by a space
    "curly": true.// Curly braces are enforced for if/for/do/while statements
    "deprecation": {
      "severity": "warn"
    },           // Issue a warning when using unrecommended APIs
    "eofline": true.// The file has a newline ending
    "forin": true./ / use the for... The IN statement filters the if statement
    "import-blacklist": [
      true."rxjs/Rx"].RXJS /Rx is not allowed to be directly imported
    "import-spacing": true.// Add Spaces between the keywords of import
    "indent": [
      true."spaces"].// Force indentation with Spaces
    "interface-over-type-literal": true.// Use the interface definition instead of (type T = {... })
    "label-position": true.// Only label is allowed to be placed in the appropriate position
    "max-line-length": [
      true.140].// Line breaks when line length exceeds 140
    "member-access": false.// No explicit visibility declaration for class members is required
    "member-ordering": [   // The sorting of class members makes the class easier to read, navigate, and edit
      true,
      {
        "order": [
          "static-field"."instance-field"."static-method"."instance-method"]}],"no-arg": true.// Arguments.callee is not allowed
    "no-bitwise": true.Bitwise operators are not allowed
    "no-console": [
      true."debug"."info"."time"."timeEnd"."trace"].// Lists the console methods that are not allowed
    "no-construct": true.String, Number,Boolean constructors are not allowed
    "no-debugger": true.// Debugger statements are not allowed
    "no-duplicate-super": true.// super is warned if it occurs twice in a constructor
    "no-empty": false.// Empty code blocks are allowed
    "no-empty-interface": true.// Empty interfaces are not allowed
    "no-eval": true.// Eval is not allowed
    "no-inferrable-types": [
      true."ignore-params"].Explicit type declarations are not allowed for variables or parameters initialized to numbers, strings, or booleans. Non-inferred type comments are allowed for function parameters
    "no-misused-new": true.// Warning when defining constructors for interfaces or new classes
    "no-non-null-assertion": true.// Not allowed! Postfix operators make non-NULL assertions
    "no-redundant-jsdoc": true.// Disallow JSDoc to copy TypeScript functionality
    "no-shadowed-variable": true.// Disallow shadow variable declarations
    "no-string-literal": false.// Allow obj["property"] to obtain object attributes
    "no-string-throw": true.// Throw strings directly is not allowed
    "no-switch-case-fall-through": true.// Case statements are not allowed to drop
    "no-trailing-whitespace": true.// No trailing whitespace is allowed
    "no-unnecessary-initializer": true.// Let is not allowed to initialize to undefined
    "no-unused-expression": true.// Unused expressions are not allowed
    "no-use-before-declare": true.// Undeclared variables are not allowed
    "no-var-keyword": true.// The var keyword is not allowed
    "object-literal-sort-keys": false.// Does not sort the attribute keywords in the object
    "one-line": [
      true."check-open-brace"."check-catch"."check-else"."check-whitespace"].// Require the specified tags to be on the same line as the expressions that precede them
    "prefer-const": true.Try to use const instead of let
    "quotemark": [
      true."single"].// Enforces the string to use single quotes
    "radix": true.// The radix parameters need to be set when using parseInt
    "semicolon": [
      true."always"].// Use a semicolon at the end of a sentence
    "triple-equals": [
      true."allow-null-check"].// use '===' and '! ==' to judge, allow '==' and '! Null = 'judgment
    "typedef-whitespace": [
      true,
      {
        "call-signature": "nospace"."index-signature": "nospace"."parameter": "nospace"."property-declaration": "nospace"."variable-declaration": "nospace"}].// Spaces are not allowed for the type definitions listed above
    "unified-signatures": true.// Issue a warning when two functions can be combined using rest, etc
    "variable-name": false.// Do not check the variable naming format
    "whitespace": [
      true."check-branch"."check-decl"."check-operator"."check-separator"."check-type"."check-module"."check-type-operator"].// Set the space style
    "no-output-on-prefix": true.// Name events without a prefix
    "use-input-property-decorator": true."use-output-property-decorator": true."use-host-property-decorator": true.Use the @hostProperty decorator instead of the host property of the @Component and @Directive metadata
    "no-input-rename": true.// Disallow renaming instruction input by supplying a string to the decorator
    "no-output-rename": true.// Disallow the renaming instruction output by supplying a string to the decorator
    "use-life-cycle-interface": true.// Ensure that the Implement lifecycle interface is used later
    "use-pipe-transform-interface": true.// Make sure to implement the PipeTransform interface using the @pipe decorator
    "component-class-suffix": true.// classes decorated with @Component must have the Component suffix
    "directive-class-suffix": true // Classes decorated with @directive must have a Directive suffix}}Copy the code

3 CSS/SCSS format constraint – stylelint

Stylelint is a powerful and modern CSS review tool that helps developers enforce uniform code specifications and avoid style errors.

Stylelint is powered by PostCSS, so it can also understand syntax parsed by PostCSS, such as SCSS.

Install stylelint:

npm i -D stylelint stylelint-config-recommended-scss stylelint-config-standard
Copy the code

Configuration. Stylelintrc. Json.

Stylelint-config-standard Rule reference

Stylelint-config-recommended rule reference

{
  "extends": ["stylelint-config-standard"."stylelint-config-recommended-scss"]."plugins": ["stylelint-scss"]."rules": {
    "string-quotes": "single"."property-no-unknown": true."selector-pseudo-class-no-unknown": true."at-rule-empty-line-before": [
      "always",
      {
        "except": ["blockless-after-same-name-blockless"."first-nested"."inside-block"]."ignore": ["after-comment"."first-nested"]}],"rule-empty-line-before": [
      "always",
      {
        "except": ["after-single-line-comment"."first-nested"]}],"block-no-empty": true."selector-pseudo-element-no-unknown": [
      true,
      {
        "ignorePseudoElements": ["ng-deep"]}],"selector-type-no-unknown": [
      true,
      {
        "ignoreTypes": ["/^d-/"]}],"color-hex-length": "long"."no-descending-specificity": null."font-family-no-missing-generic-family-keyword": null."no-duplicate-selectors": null."declaration-block-no-duplicate-properties": [
      true,
      {
        "ignore": ["consecutive-duplicates"}]}}Copy the code

4 Git message constraint – commitlint

Like Tslint, commitLint itself only provides the functionality for checking and some of the most basic rules. Users need to configure their own specifications based on these rules.

For the Conventional Commits specification, the community has the @commitlint/ config-Conventional package ready, and we simply need to install and enable it.

Install commitlint:

npm i -D @commitlint/cli @commitlint/config-conventional
Copy the code

Configuration commitlint. Config. Js:

const types = ['feat'.'fix'.'docs'.'style'.'refactor'.'perf'.'test'.'build'.'release'.'chore'.'revert'];

module.exports = {
  extends: ['@commitlint/config-conventional'].rules: {
    'type-empty': [2.'never'].'type-enum': [2.'always', types],
    'scope-case': [0.'always'].'subject-empty': [2.'never'].'subject-case': [0.'never'].'header-max-length': [2.'always'.88],}};Copy the code

After configuring Lint above, you can constrain submitted messages.

Message format Reference

5 Configure the NPM script

If we want to configure the modified format command, we need to configure the corresponding command in package.json.

Package. Json to scripts:

{..."scripts": {..."lint:devui": "tslint -p devui/tsconfig.lint.json -c devui/tslint.json \"devui/**/*.ts\""."lint:devui:fix": "tslint --fix -p devui/tsconfig.lint.json -c devui/tslint.json \"devui/**/*.ts\""."prettier": "prettier --config ./.prettierrc --write \"{devui,src}/**/*.html\""."stylelint": "stylelint \"{devui,src}/**/*.{scss,css}\" --fix". },... }Copy the code

NPM run lint:devui files can be automatically corrected using NPM run lint:devui.

6 Configure automatic modification of Git submission codes

To fix the staging code automatically during git commit, you can configure git hook associations (see Git hooks). First you need to install:

npm i -D lint-staged husky
Copy the code

Lint-staged allows us to run Lint commands on staging areas to format only what needs to be submitted.

Husky lets us associate git hooks and perform required command operations.

  1. Add lint-staged items to package.json:
{..."lint-staged": {
    "devui/**/*.ts": [
      "tslint --fix -p devui/tsconfig.lint.json -c devui/tslint.json \"*.ts\""."git add"]."src/**/*.ts": [
      "tslint --fix -c src/tslint.json \"*.ts\""."git add"]."{devui,src}/**/*.html": [
      "prettier --config ./.prettierrc --write"."git add"]."{devui,src}/**/*.{scss,css}": [
      "stylelint --fix"."git add"]},... }Copy the code
  1. Husky adds lint-staged association to package.json:
{..."husky": {
    "hooks": {
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS && node ./scripts/commit-lint/commit-lint.js HUSKY_GIT_PARAMS"."pre-commit": "lint-staged"}},... }Copy the code

After the above configuration is complete, automatic format correction and error interception can be carried out for.ts files in git code submission stage.

7 Configure the VSCode project uniformly

VSCode provides the ability to set the project uniformly. You only need to write the corresponding configuration items in the. VSCode directory.

Configure.vscode/extensions.json to set the unified plugin:

{
	// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
	// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
	// List of extensions which should be recommended for users of this workspace.
	"recommendations": [
		/* use the latest version of VSCODE, after opening the project, there is a prompt to install all plug-ins in the lower right corner, and the left side of the plug-in column lists the workspace plug-ins */
		/*Angular developer artifact */
		"angular.ng-template"./*Angular,typescript, HTML, etc. Syntax padding */
		"mikael.angular-beastcode"./*DevUI component library hover prompt, autocomplete plug-in */
		"sspkudevui.devuihelper"./* Check the spelling of words in the code */
		"streetsidesoftware.code-spell-checker"./*ts static check */
		"ms-vscode.vscode-typescript-tslint-plugin"./* static check */
		"stuartzhang.stylelint-stzhang"./* Color bracket pairing */
		"coenraads.bracket-pair-colorizer-2"./* Git changes appear in the code */
		"eamodio.gitlens"./ * * / markdown inspection
		"davidanson.vscode-markdownlint"./* Duplicate code detection */
		"paulhoughton.vscode-jscpd"./* Chinese package */
		"ms-ceintl.vscode-language-pack-zh-hans"].// List of extensions recommended by VS Code that should not be recommended for users of this workspace.
	"unwantedRecommendations": []}Copy the code

Vscode /settings.json to configure the current project Settings:

{
    "jscpd.files":"devui/*/*"."editor.codeActionsOnSave": {
        "source.organizeImports": true  // Format each import}}Copy the code

summary

This article describes how the Ng-devui component library applies format constraints to projects, describes the various Lint tools currently in use, and how to set git commit access and format automatic repair through association.

More importantly, if you use VSCode, it provides a unified configuration reference for your project.

By providing methods and steps in this article, you can make your project lint conformance constrained.

Note:

  • The TSLint tool mentioned in this article has stopped updating, ESLint is now preferred, and ng-devui is already being switched.

  • Ng-devui package.json Complete reference: github.com/DevCloudFE/… .

Join us

We are DevUI team, welcome to come here and build elegant and efficient human-computer design/research and development system with us. Email: [email protected].

DevUI Bang bang bang bang

Previous articles are recommended

Learn to write Unit Test Cases with Huawei DevUI Open Source Component Library

Start writing Tests for Your Angular App now, Part 2

Baking cookies under a Waterfall: Three Steps to Quickly Locate Performance Issues