preface

I’ve been learning typescript, also known as TS, which is a superset of JS. The specific introduction is not to say, today is mainly to take you with Webpack from zero to build a TS development environment. It is too tedious to compile directly with the traditional TSC xx.ts file, which is not beneficial to our development. After this manual configuration, we can also know how vue3 internal configuration of TS webpack, without talking about the main topic.

The Node to compile TS

Let’s start with how to run ts files. The most traditional way is of course to type commands directly

tsc xxx.ts

Of course, you must have installed TS first. If not, run the following command

npm install typescript -g

Check the version after installation

tsc –version

Now we have the compiled JS file, and we can use the Node directive

node xxx.js

Of course, you can also create a new HTML page to import compiled JS files

Can you compile TS directly from Node? The following is an introduction to this method using TS-Node to get the desired installation

npm install ts-node -g

In addition, TS-Node relies on tslib and @types/node packages, which need to be downloaded

npm install tslib @types/node -g

We can now run TypeScript code directly from TS-Node

ts-node xxx.ts

If we encountered a lot of TS files, this approach would be tedious, so we had better use WebPack to build a TS development environment, which is the best solution.

Webpack setup preparation

Create a new folder to download Webpack webpack-CLI

npm install webpack webpack-cli -D

Download TS Tsloader

npm install typescript ts-loader -D

Download webpack-dev-server

npm install webpack-dev-server -D

Download the HTML template plug-in

npm install html-webpack-plugin -D

Initialize the webpack

npm init

Initialize the ts

tsc –init

Create the configuration file webpack.config.js

After initialization, the file structure is shown below. Of course, some test TS and HTML need to be created manually

Webpack configuration

Let’s add two run and package directives to package.json before configuration

webpack.config.js

This is explained in the code

Const HtmlWebpackPlugin = require('html-webpack-plugin')// Introduce template components Module. exports = {mode: 'development',// development mode entry: './ SRC /main.ts',// export file address output: {path: Path. resolve(__dirname, "./dist"), devServer: {}, resolve: {extensions: [' ts', 'js',' CJS ', 'json'] / / configuration file into omit the suffix}, the module: {rules: [{test: }]}, plugins: [new HtmlWebpackPlugin({template: './index.html' // Use template address})]}Copy the code

The configuration is complete and we’re ready to test. Follow instructions

npm run serve

Packing instructions

npm run build

End

Give it a thumbs up when you’re done