本章演示如何将tsx转为js
webpack从0开始搭建react的ts开发环境(5)
demo https://github.com/757566833/webpack-guide
1.添加types
yarn add @types/react-dom @types/react --dev
2.将src/app.ts改为app.tsx
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
public render() {
return (
<div>
hello react
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
3.将webpack.config.js的入口改为tsx
// ts-loader自带支持react,并非像jsx转js时候,需要添加好多的babel全家桶
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: './src/app.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js'
},
module: {
rules: [{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/,
}]
},
plugins: [
new HtmlWebpackPlugin({
title: "test",
template: path.resolve(__dirname, "template.html"),
})
]
};
4.修改tsconfig.json
...
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true,
...
5.npm run webpack
6.打开dist下的html