这次的目标: 添加TypeScript
- 安装
yarn add typescript awesome-typescript-loader source-map-loader --dev
- 添加TypeScript配置文件
// tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
},
"include": [
"./src/**/*"
]
}
- 写一些代码
把入口文件改为ts格式: index.js -> index.ts, 并给greetings一个类型:
// src/index.ts
import './index.css';
const greetings: string = 'Hello world!';
document.getElementById('root').innerText = greetings;
- 修改webpack配置
// webpack.config.js
// ...
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{ enforce: 'pre', test: /\.js$/, loader: 'source-map-loader' },
{
oneOf: [
{ test: /\.ts$/, loader: 'awesome-typescript-loader' },
// ...
]
}
]
},
resolve: {
extensions: ['.ts', '.js', '.json'],
},
// ...
}
- 测试
执行yarn start
, 成功了!