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:
这里写图片描述

运行npm run start 会发现在目录中多了一个dist目录
这里写图片描述

6.在dist新建index.html
将bundle.js引入到此文件中。在浏览器打开,查看控制台:
这里写图片描述
表示运行成功。
7.引入热更新

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

在script加上这样一段:

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

再次运行npm run dev
这里写图片描述
表示运行成功。按其提示在浏览器打开,修改代码,查看运行的效果。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值