最近准备自己造一套轮子,技术栈暂定为react+typescript。在react引入ts的时候还是遇到了一些坑,所以写篇文章记录一下引入的过程。
引入ts么,就要先选择一个ts的解析工具,这里我根据文档选了awesome-typescript-loader,所以在webpack.config.js里加
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'awesome-typescript-loader'
}
]
},
然后配置ts.config.js文件,在配置的时候,我加了这样一个选项
"allowSyntheticDefaultImports": true
然后在yarn test的时候出现了一些bug,引入react必须import * as React from 'react'这么引, 否则就出错,报错如下
Cannot read property 'createElement' of undefined
必须把它改成
"esModuleInterop": true,
所以ts.config.js配置应如下
{
"compilerOptions": {
"declaration": true,
"baseUrl": ".",
"paths": {
"utils/*": ["include/utils/*"],
"stylesheets": ["stylesheets/"],
"examples": ["examples/"]
},
"rootDirs": ["include"],
"outDir": "dist",
"module": "esnext",
"target": "es5",
"lib": ["es6", "dom"],
"sourceMap": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": ".",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"importHelpers": true,
"strictNullChecks": true,
"esModuleInterop": true,
"noUnusedLocals": true
},
"include": [ // 所需要用ts的文件
"lib/**/*",
"types/**/*",
],
"exclude": [ //排除文件
"node_modules",
"build",
"dist",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts",
"*.js"
]
}
另外,我需要再引入一下tslint,所以还要配置一个
tslint
{
"extends": [
"tslint:recommended",
"tslint-react"
],
"rules": {
"no-console": [
false,
"log",
"error"
],
"jsx-no-multiline-js": false,
"whitespace": false,
"no-empty-interface": false,
"space-before-function-paren": false,
"no-namespace": false,
"label-position": false,
"quotemark": [
true,
"single",
"jsx-double"
],
"member-access": false,
"semicolon": [
true,
"always",
"ignore-bound-class-methods"
],
"no-unused-expression": [
true,
"allow-fast-null-checks"
],
"member-ordering": false,
"trailing-comma": false,
"arrow-parens": false,
"jsx-self-close": false,
"max-line-length": false,
"interface-name": false,
"no-empty": false,
"comment-format": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"eofline": false,
"jsx-no-lambda": false,
"no-trailing-whitespace": false,
"jsx-alignment": false,
"jsx-wrap-multiline": false,
"no-shadowed-variable": [
false,
{
"class": true,
"enum": true,
"function": false,
"interface": false,
"namespace": true,
"typeAlias": false,
"typeParameter": false
}
]
},
"linterOptions": {
"exclude": [
"config/**/*.js",
"node_modules/**/*.ts",
"coverage/lcov-report/*.js"
]
}
}
配置完成,下一节我会讲react里怎么使用ts。