- 安装必要的依赖:
npm i typescript ts-loader webpack webpack-cli webpack-dev-server -D
- 初始化
tsconfig.json
配置文件:
npx tsc --init
- 修改
tsconfig.json
文件中的以下配置:
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"sourceMap": true,
"outDir": "./dist",
"moduleResolution": "node",
"esModuleInterop": true,
"allowJs": true
}
}
- 修改 webpack 配置文件:
module.exports = {
entry: './src/index.ts', // 入口文件为 .ts 文件
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'], // 添加 .tsx 和 .ts 后缀名
},
output: {
path: path.resolve(__dirname, 'dist'), // 输出路径
filename: 'bundle.js', // 输出文件名
},
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 9000,
},
}
- 修改
package.json
文件中的启动脚本:
{
"scripts": {
"start": "webpack serve --open"
}
}
- 创建一个
index.ts
文件并在其中编写一些 TypeScript 代码,然后运行 npm start
命令启动开发服务器。打开 http://localhost:9000
查看运行结果。