antd + typescript 踩坑实录
提醒:本文最后更新于 4 年前
,文中所描述的信息可能已发生改变,请谨慎使用。
编译构建使用 awesome-typescript-loader 进行编译。
tsconfig 参数需要指定
{
"compilerOptions": {
"module": "es2015", // 注意,需要保留 es2015 的 import 语法供 babel 转
"target": "es2015",
"moduleResolution": "node", // es2015 需要指定 node
"noImplicitAny": false,
"sourceMap": false,
"jsx": "preserve",
"experimentalDecorators": true,
"skipDefaultLibCheck": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"lib": [
"dom",
"es5",
"es2015",
"es2016",
"es2017"
]
},
"awesomeTypescriptLoaderOptions": {
"useWebpackText": true,
"useCache": true,
"useBabel": true
}
}
这样才能保证
import Button from 'antd/lib/button`
时不会报 undefined
的错误。
简单原因分析,antd 子模块是 ES2015 模块标准,如果使用 ts 编译为 const Button = require('antd/lib/button').default
之后 babel 再次编译,webpack 会把模块当 commonjs 模块去解析,最后的结果会变成 const Button = require('antd/lib/button').default.default
就挂了