Webpack4与Typescript结合开发

源代码:https://github.com/fengjutian/ts-webpack
1.创建工程
mkdir ts-webpack
使用npm init 工程
安装:

npm install --save-dev webpack webpack-cli
npm install --save-dev typescript ts-loader

2.创建tsconfig.json

  {
    "compilerOptions": {
      "outDir": "./dist/",
+     "sourceMap": true,
      "noImplicitAny": true,
      "module": "commonjs",
      "target": "es5",
      "jsx": "react",
      "allowJs": true
    }
  }

3.创建webpack.config.js

  const path = require('path');

  module.exports = {
    entry: './src/index.ts',
+   devtool: 'inline-source-map',
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: 'ts-loader',
          exclude: /node_modules/
        }
      ]
    },
    resolve: {
      extensions: [ '.tsx', '.ts', '.js' ]
    },
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

4.创建src目录
写下一段ts代码:

class Shape {
    area: number;
    color: string;
    constructor ( name: string, width: number, height: number ) {
        this.area = width * height;
        this.color = "pink";
    };

    shoutout() {
        return "I'm " + this.color + " with an area of " + this.area + " cm squared.";
    }
}

var square = new Shape("square", 30, 30);
console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
console.log( 'Color of Shape: ' + square.color );

5.在scrip加一段start:
Webpack4与Typescript结合开发_第1张图片

运行npm run start 会发现在目录中多了一个dist目录
Webpack4与Typescript结合开发_第2张图片

6.在dist新建index.html
将bundle.js引入到此文件中。在浏览器打开,查看控制台:
Webpack4与Typescript结合开发_第3张图片
表示运行成功。
7.引入热更新

npm install webpack-dev-server --save-dev

在script加上这样一段:

"dev":"npx webpack-dev-server --mode development --content-base ./dist"

再次运行npm run dev
Webpack4与Typescript结合开发_第4张图片
表示运行成功。按其提示在浏览器打开,修改代码,查看运行的效果。

你可能感兴趣的:(webpack)