webpack4之ts配置


配置

注意: TypeScript 不会做 Polyfill,例如从 es6 编译到 es5,TypeScript 编译后不会处理 es6 的那些新增的对象的方法,如果需要 polyfill 需要自行处理!

听说ts配置
官方ts配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# npm i -D webpack webpack-cli ts-loader typescript
# npm i -g ts-node // ts-node demo.ts可以执行ts文件里的代码并输出到命令行

// tsconfig.json
{
"compilerOptions": {
"outDir": "./dist", // 把打包生成文件打包到dist目录,可忽略
"module": "es6", // 用es6的语法
"target": "es5", // 打包最终生成ES5语法
"allowJs": true, // 允许引入js文件
"experimentalDecorators": true // 支持装饰器
}
}

// webpack.config.js
const path = require('path')

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

// index.ts
class Greeter {
greeting: string
constructor (message: string) {
this.greeting = message
}
greet () {
return 'hello,' + this.greeting
}
}

let greeter = new Greeter('world')
let button = document.createElement('button')
button.textContent = 'say hello'
button.onclick = function () {
alert(greeter.greet())
}

document.body.append(button)
```

##### ts安装依赖包
> 按照正常的安装依赖包,引入依赖的时候不会有类型判断,所以需要再安装一个依赖包对应的typescript的类型文件

// 判断该依赖包是否有ts的类型文件
// github搜索types,找到DefinitelyTyped项目,打开官网:http://definitelytyped.org/,有使用方法和搜索功能,可以搜索该依赖包是否有类型文件
// npm install –save-dev @types/lodash

// index.ts
import * as from ‘lodash’
console.log(111,
.join([1,2], ‘-‘))
```