源代码: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 );
运行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"