If you have any errors, please contact the author. Analysis code word is not easy, reproduced please indicate the source, thank you!

This article documents configuration and package selection in typescript projects, where dependencies and best practices are evolving, with the repository MVVM as the latest configuration.

Typescript support

The use of Babel 7.0 + in Webpack abandons the traditional TS-loader or awesome-typescript-loader scheme. Here’s why:

  • Reference 1
  • Reference 2
yarn add @babel/core babel-loader @babel/preset-env @babel/preset-typescript -D yarn add @babel/plugin-proposal-class-propertie -d // Add other escape plug-ins not included in env according to project requirementsCopy the code

Babel is only responsible for the conversion and does not do the corresponding type checking, so you need to install the fork-ts-checker-webpack-plugin to report the error:

yarn add fork-ts-checker-webpack-plugin -D
Copy the code

General project to ES5 installation package:

yarn add @babel/plugin-transform-runtime @babel/runtime-corejs3 -D
Copy the code

Babel. Config. Js:

module.exports = {
  presets: [['@babel/env',
      {
        targets: '> 1%, not dead'}].'@babel/preset-typescript'].plugins: [['@babel/plugin-transform-runtime',
      {
        corejs: 3}].'@babel/plugin-proposal-class-properties']};Copy the code

Tsconfig. Json configuration:

{
  "compilerOptions": {
    "target": "ESNext"."module": "commonjs"."noImplicitAny": true."sourceMap": false
  },
  "include": ["src/**/*"]}Copy the code

Webpack configuration:

module: {
  rules: [{test: /\.(js|ts)$/.exclude: /(node_modules|bower_components)/.use: ['babel-loader']}]; }Copy the code

Code review & style uniformity

Code checks use ESLint (official future recommendation), discarding the traditional TSLint scheme: see link.

Yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin -d //@typescript-eslint/parser: typescript // @typescript-esLint /eslint-plugin: just a list of rules that can be turned on or offCopy the code

@typescript-eslint/parser as the parser for Babel, there is no need to install the default recommended ESLint parser for Babel (babel-eslint).

Prettier: Add parser to configuration file prettier. Config.js in a typescript project “Typescript” is enough (provided @typescript-esLint /parser: reference link is installed).

Project Generic Prettier other packages:

yarn add prettier eslint-config-prettier eslint-plugin-prettier -D
Copy the code

Eslint +prettier

prettier.config.js:

module.exports = {
  singleQuote: false.printWidth: 200.parser: 'typescript'
};
Copy the code

.eslintrc.js (the default Google rule eslint-config-google used here):

module.exports = {
  root: true.parser: '@typescript-eslint/parser'.plugins: ['@typescript-eslint'].env: {
    browser: true.es6: true
  },
  extends: ['plugin:@typescript-eslint/recommended'.'google'.'prettier'.'prettier/@typescript-eslint'].globals: {
    Atomics: 'readonly'.SharedArrayBuffer: 'readonly'
  },
  parserOptions: {
    ecmaVersion: 2018.sourceType: 'module'
  },
  rules: {
    '@typescript-eslint/no-explicit-any': 0.'@typescript-eslint/no-use-before-define': 0}};Copy the code

Unit testing

jest

Here choose JEST framework to test. The advantage of JEST? .

In the TS project, traditional TS-Jest is abandoned, just install @babel/preset-typescript as above and add presets in babel.config.js. Reference link.

Yarn jest @types/jest -d //@types/jest is the ts type definition file of jest, and vscode is based on ts code promptCopy the code
  • After the checkjestFound in the dependency pack,jestRely onbabel-jest(For supportes6Syntax), so there is no need to introduce dependency packages separatelybabel-jest.
  • Because of the introduction of@types/jest, there is no need to introduceeslint-plugin-jestTo eliminate thejestVariable error.
  • jest configUse the default configuration, more personalized configurationsee.

coveralls

Coveralls was chosen as an online tool to automatically test code coverage. Since the project goes through continuous integration with Travis.com, the configuration is:

yarn add coveralls -D
Copy the code

.coveralls.yml:

service_name: travis-pro
repo_token: COVERALLS_TOKEN # COVERALLS_TOKEN is an encrypted variable
Copy the code

Package. json add scripts (test framework is Jest, see more methods):

  "scripts": {
    "coveralls": "jest --coverage && cat ./coverage/lcov.info | coveralls"
  },
Copy the code

. Travis. Yml to add:

script:
  - sed -i "s/COVERALLS_TOKEN/$COVERALLS_TOKEN/" .coveralls.yml #$COVERALLS_TOKEN is an encrypted variable configured in the Travis.com project
  - yarn run coveralls
Copy the code

Debug node.js like jest/webpack in vscode

Debug -> Add Configuration -> Select Node. js to automatically generate.vscode/launch.json and change the configuration to:

The document

"Configurations ": [{"type": "node", // System default, unmodifiable, identifies the type of the debugger to be used "request": "Launch ", // System default, unchangeable, launches debugger program on specified file. Attach: attach debugger to already running process. "${workspaceFolder}/index.js", // The absolute path of the node.js program to be debugged "args": ["--runInBand", "--env=jsdom", "${fileBasename}"], "NPM ", // The absolute path to the runtime executable to use. The default is the node (https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_launch-configuration-support-for-npm-and-other-tools) "RuntimeArgs ": ["run-script", "debug"], // Optional parameter passed to the runtime executable "runtimeVersion":"7.10.1", // Using NVM can use this property to control node.js version "port": // The debug port to use "console": "externalTerminal", // specify how to display program output: ExternalTerminal: standalone console window,integratedTerminal(default):VS code integration terminal "stopOnEntry": True, // When set to true, the debugger is broken on the first line of the debugger. If omitted (the default) or set to false, the debugger runs to the first breakpoint. [" < node_internals > / * * / *. Js ", "${workspaceFolder} / lib / * * / *. Js"] / / skip are not interested in the code, Node. Js's built-in core module is defined as: < node_internals >, other variable definition (https://code.visualstudio.com/docs/editor/variables-reference)}]Copy the code
  • Commissioning of the singlenodeFile:
    • launch.jsonConfiguration:
      • program:${workspaceFolder}/index.js
      • args:['--dev']
  • debuggingnpm scripts(Including ordinarynodeCommand such asindex.jsAnd thenodeCommand such asjest,webpackWhen, etc.) :
    • launch.jsonConfiguration:
      • runtimeExecutable:"npm"// Must be set tonpm
      • runtimeArgs:["run", "debug"]The first argument must berun
      • RuntimeVersion: "10.6.0"/ / is optional
    • package.jsonnpm scriptsConfiguration:
      • Have to add--inspect-brk=5858.5858portSettings must be the same
      • Non-common commands need to be converted tonodeCall:webpack=>./node_modules/.bin/webpack(because thenpm run buildWhat’s actually called isnode_modules/.bin/webpack)
      • The command with arguments follows:node --inspect-brk=5858 ./node_modules/.bin/jest --coverage

npm scripts:

  "scripts": {
    "debug": "node --inspect-brk=5858 index.js",
    "build": "node --inspect-brk=5858 ./node_modules/.bin/webpack --mode=development",
    "test": "node --inspect-brk=5858 ./node_modules/.bin/jest --coverage"
  },
Copy the code

Front-end testing concepts

Test type

  • Unit tests (Unit Test) – Tests independent functions or classes by simulating inputs and predicting outputs.
  • Integration testing (Integration Test) – Tests whether the linkage between multiple modules is as expected.
  • E2ETesting (also known as testingFunctional Test) – The focus is not on internal implementations, but on testing whether the product can achieve the desired results in real use scenarios (such as browsers). This is black box testing.

More and more

other

Typescript errors are ignored

  • Single line to ignore// @ts-ignore
  • Ignore the full// @ts-nocheck
  • Cancel ignore full text// @ts-check

Making the badge

Shields spawn any badge.

What are.d.ts files

D. ts is the TypedDefinition type definition file that defines type information and interface specifications.

Ts code is eventually compiled into.js js code for others to use. At this point the type information is lost. Therefore, the ts compiler will automatically generate external.d.ts files based on the information in the.ts file, and the generated JS file to use. The js file is used to run the engine, while the.d.ts file is used to write code for the IDE (intelligent editor).

How do I test a local Node package

Using NPM link

  • In packages that need to be tested (e.gtest) path to execute:npm link, at this momentGlobal node_modulesYou can see this under the bagtestThe package.
  • Install the test package under the project of the target package you want to reference:npm link testAdd scope if there is scope:npm link @fe_korey/test), then the test package is installed in the directory, in thetestChanges in the package are synchronized to the target package.
  • Unconnect: intestBag execution:npm unlinkCan.

Note: In the WebPack project, if you test local packages using NPM link, you need to set config:

resolve: {
  symlinks: false;
}
Copy the code