最近在学习ts,想引入原来的react项目,学习了一些资料,记录以备后续使用
一.添加TS的编译器
1.安装依赖
ts-loader帮助我们ts转换成js,Source-map-loader方便调试
npm install --save-dev typescript ts-loader source-map-loader
获取类型定义的文件
npm install --save @types/react @types/react-dom
tips:如果你用的老版本的React or ReacDOM和@type不符合,可以在package.json中指定@types/react or @types/react-dom的版本号
2.配置TS
创建tsconfig.json工程配置文件,增加相关配置
{
"compilerOptions": {
"outDir": "./dist/", // 输出目录的路径
"sourceMap": true, // 容许sourceMap
"strictNullChecks": true, // 启用严格的null检查
"module": "es6", // 指定模块的生成代码模式
"jsx": "react", // 用ts将jsx转换成js
"target": "es5", // 指定esc的目标版本
"allowJs": true // 接受JavaScript做为输入
},
"include": [
"./src/"
]
}
其他配置可参考: blog.csdn.net/weixin_4329…
二:配置webpack
更改webpack.config.js文件
module.exports = {
// change to .tsx if necessary
entry: './src/app.jsx',
output: {
filename: './bundle.js'
},
resolve: {
// changed from extensions: [".js", ".jsx"]
extensions: [".ts", ".tsx", ".js", ".jsx"]
},
module: {
rules: [
// changed from { test: /\.jsx?$/, use: { loader: 'babel-loader' }, exclude: /node_modules/ },
{ test: /\.(t|j)sx?$/, use: { loader: 'ts-loader' }, exclude: /node_modules/ },
// addition - add source-map support
{ enforce: "pre", test: /\.js$/, exclude: /node_modules/, loader: "source-map-loader" }
]
},
externals: {
"react": "React",
"react-dom": "ReactDOM",
},
// addition - add source-map support
devtool: "source-map"
}