1、新建工程目錄,進入目錄,輸入 npm init -y (-y是yes的意思,不詢問設(shè)置,按照默認初始化);
2、安裝react/react-dom:npm install --save react react-dom;
3、安裝react和react-dom的聲明文件:npm install --save-dev @types/react @types/react-dom;
4、安裝typescript和相關(guān)loader: npm install --save-dev typescript ts-loader source-map-loader;
5、安裝插件html-webpack-plugin,該插件:npm install --save-dev html-webpack-plugin,該插件是可選的,作用是自動生成html,并自動引入最終打包好的js文件;
6、安裝webpack相關(guān),```npm install --save-dev webpack-dev-server webpack webpack-cli;
7、在項目根目錄創(chuàng)建typescript配置文件tsconfig.json:
{
"compilerOptions": {
"sourceMap": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
}
}
8、創(chuàng)建webpack配置文件:webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: "./src/index.tsx",
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, "dist")
},
devServer:{
port: 9001,
open: true,
contentBase: "./dist"
},
module: {
rules: [
{
test: /\.tsx?$/,
use: {
loader: 'ts-loader'
},
exclude: /node_modules/
},
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
plugins: [
new HtmlWebpackPlugin({
title: "hello dog",
hash: false,
// template: path.resolve(__dirname, "src/index.html")
}),
]
}
9、編輯package.json,在script里增加"start": "webpack-dev-server";
10、創(chuàng)建入口文件index.tsx,這里可以愉快的寫代碼了;
11、npm start運行
以下步驟可選。由typescript語法寫的代碼,經(jīng)過ts-loader可以成功轉(zhuǎn)換為瀏覽器可以識別的js代碼,也包括jsx語法,因為tsconfig.json中配置了"jsx": "react"。轉(zhuǎn)換jsx語法的任務(wù)也可以交給babel,只要將jsx指定為preserve,然后指定babel-loader進行下一步轉(zhuǎn)化,這個過程需要用到@babel/preset-react預(yù)設(shè)。
12、安裝babel npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/preset-react;
13、添加babel配置文件babel.config.js:
const presets = [
[
"@babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
},
],
[
"@babel/preset-react"
]
];
module.exports = { presets };
presets是按照逆序執(zhí)行的
14、修改webpack.config.js文件,添加babel-loader:
rules: [
{
test: /\.tsx?$/,
loader:['babel-loader','ts-loader'],
exclude: /node_modules/
},
]