Know the TypeScript

TypeScript officially provides a compiler that converts TypeScript to JavaScript. You need to create a new tsconfig.json file in the current project root directory to configure the compilation options

{
  "compilerOptions": {
    "module": "commonjs".// The module specification used by the compiled code
    "target": "es5".// Which version of ES does the compiled code use
    "sourceMap": true // Output Source Map to facilitate debugging
  },
  "exclude": [ // Do not compile the files in these directories
    "node_modules"]}Copy the code

After installing the compiler globally with NPM install -g typescript, you can compile hello.js and hello.js.map files using the TSC hello.ts command

Reduce code redundancy

To prevent the same helper functions from reappearing in multiple files, you can enable importHelpers in the TypeScript compiler and modify the tsconfig.json file as follows:

{
  "compilerOptions": {
    "importHelpers": true}}Copy the code

Integrated Webpack

  1. Convert TypeScript to JavaScript by Loader.
  2. Webpack needs to try to find the corresponding file for the moduletsThe suffix.

The faster awesome-typescript-loader is recommended

The Webpack configuration is as follows:

const path = require('path');

module.exports = {
  // Execute the entry file
  entry: './main'.output: {
    filename: 'bundle.js'.path: path.resolve(__dirname, './dist'),},resolve: {
    // Try the TypeScript source files with the TS suffix first
    extensions: ['.ts'.'.js']},module: {
    rules: [{test: /\.ts$/,
        loader: 'awesome-typescript-loader'}},devtool: 'source-map'.// Output Source Map to debug TypeScript code in the browser
};
Copy the code

The dependencies used above need to be installed before running the build:

npm i -D typescript awesome-typescript-loader
Copy the code

After the installation is successful and the build is executed again, you should see the output JavaScript file bundle.js in the dist directory, and the corresponding Source Map file bundle.js.map. After opening the index.html page in your browser, you can view and debug TypeScript source code in the development tool.