webpack typescript react 组合开发环境搭建

1、新建工程目录,进入目录,输入 npm init -y (-y是yes的意思,不询问设置,按照默认初始化);
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和相关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相关,```npm install --save-dev webpack-dev-server webpack webpack-cli;
7、在项目根目录创建typescript配置文件tsconfig.json:

{
    "compilerOptions": {
      "sourceMap": true,
      "module": "commonjs",
      "target": "es5",
      "jsx": "react",
    }
  }

8、创建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、创建入口文件index.tsx,这里可以愉快的写代码了;
11、npm start运行
以下步骤可选。由typescript语法写的代码,经过ts-loader可以成功转换为浏览器可以识别的js代码,也包括jsx语法,因为tsconfig.json中配置了"jsx": "react"。转换jsx语法的任务也可以交给babel,只要将jsx指定为preserve,然后指定babel-loader进行下一步转化,这个过程需要用到@babel/preset-react预设。
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是按照逆序执行的
14、修改webpack.config.js文件,添加babel-loader:

rules: [
            {
                test: /\.tsx?$/,
                loader:['babel-loader','ts-loader'],
                exclude: /node_modules/
            },
        ]

你可能感兴趣的:(webpack typescript react 组合开发环境搭建)