美文网首页
webpack5.0 搭建react+ts框架 亲测~

webpack5.0 搭建react+ts框架 亲测~

作者: 卓小生 | 来源:发表于2022-06-30 09:41 被阅读0次

    初始化

    npm init -y

    package.json文件

    {
      "name": "react",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "dev": "cross-env state=dev webpack-dev-server --config ./webpack-config/webpack.dev.js",
        "dev:test": "cross-env state=test webpack-dev-server --config ./webpack-config/webpack.dev.js",
        "build": "cross-env state=prod webpack --config ./webpack-config/webpack.prod.js",
        "build:test": "cross-env state=test webpack --config ./webpack-config/webpack.prod.js"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "@babel/core": "^7.18.6",
        "@babel/preset-env": "^7.18.6",
        "@babel/preset-react": "^7.18.6",
        "@babel/preset-typescript": "^7.18.6",
        "babel-loader": "^8.2.5",
        "clean-webpack-plugin": "^4.0.0",
        "cross-env": "^7.0.3",
        "css-loader": "^6.7.1",
        "fork-ts-checker-webpack-plugin": "^7.2.11",
        "html-webpack-plugin": "^5.5.0",
        "mini-css-extract-plugin": "^2.6.1",
        "node-sass": "^7.0.1",
        "postcss-loader": "^7.0.0",
        "react": "^18.2.0",
        "react-dom": "^18.2.0",
        "react-router-dom": "^6.3.0",
        "sass-loader": "^13.0.2",
        "style-loader": "^3.3.1",
        "webpack": "^5.73.0",
        "webpack-cli": "^4.10.0",
        "webpack-merge": "^5.8.0"
      },
      "devDependencies": {
        "@types/react": "^18.0.14",
        "@types/react-dom": "^18.0.5",
        "ts-loader": "^9.3.1",
        "typescript": "^4.7.4",
        "webpack-dev-server": "^4.9.2",
        "webpackbar": "^5.0.2"
      }
    }
    
    

    目录结构

    image.png

    tsconfig.json

    {
      "compilerOptions": {
        "baseUrl": ".",
        "target": "es2015",
        "jsx": "react-jsx",
        "strict": true,
        "module": "esnext",
        "importHelpers": true,
        "moduleResolution": "Node",
        "allowSyntheticDefaultImports": true,
        "paths": {
          "@/*": ["src/*"]
        }
      },
      "include": ["src/**/*", "types/*.d.ts", "test.js"],
      "exclude": ["node_modules"]
    }
    
    

    config相关文件

    // webpack.common.js
    
    const Webpack = require("webpack");
    const Path = require("path");
    
    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const { CleanWebpackPlugin } = require("clean-webpack-plugin");
    const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    const getCSSModuleLocalIdent = require("react-dev-utils/getCSSModuleLocalIdent");
    const WebpackBar = require("webpackbar");
    
    const ENV_STATE = process.env.state;
    const util = require("./util");
    
    const modules = {
      rules: [
        {
          test: /\.(js|jsx)$/,
          loader: "babel-loader",
          exclude: /node_modules/,
        },
        {
          test: /\.(ts|tsx)$/,
          loader: "ts-loader",
          exclude: /node_modules/,
        },
        {
          test: /\.(css|scss)$/,
          exclude: /\.module\.scss$/,
          use: [
            MiniCssExtractPlugin.loader,
            "css-loader",
            "postcss-loader",
            "sass-loader",
          ],
        },
        {
          test: /\.module\.scss$/,
          use: [
            MiniCssExtractPlugin.loader,
            {
              loader: "css-loader",
              options: {
                modules: {
                  getLocalIdent: getCSSModuleLocalIdent, // 命名带地址
                },
              },
            },
            "postcss-loader",
            "sass-loader",
          ],
        },
      ],
    };
    
    const plugins = [
      // html模板
      new HtmlWebpackPlugin({
        template: "index.html",
      }),
      //   css压缩
      new MiniCssExtractPlugin({
        filename: "css/[name].[hash].css",
      }),
      // 打包显示进度条
      new WebpackBar(),
      new Webpack.DefinePlugin({
        "process.env": {
          STATE_CONFIG: JSON.stringify(util.url[ENV_STATE]),
        },
      }),
      // webpack打包不会有类型检查,强制ts类型检查
      new ForkTsCheckerWebpackPlugin({
        typescript: {
          configFile: Path.resolve(__dirname, '..', "tsconfig.json"),
        },
      }),
      // 自动删除上一次打包的产物
      new CleanWebpackPlugin(),
    ];
    
    module.exports = {
      entry: "./src/index.tsx",
      output: {
        path: Path.resolve(__dirname, `../${util.outPath[ENV_STATE]}`),
        filename: "./js/[name].[hash].js",
        clean: true,
        publicPath: "/",
      },
      resolve: {
        alias: {
          "@": Path.resolve(__dirname, "../src"),
        },
        extensions: [".ts", ".tsx", ".js", ".jsx"],
      },
      module: modules,
      plugins,
      cache: {
        type: "filesystem",
        // 可选配置
        buildDependencies: {
          config: [__filename], // 当构建依赖的config文件(通过 require 依赖)内容发生变化时,缓存失效
        },
        name: "development-cache",
      },
    };
    
    
    // webpack.dev.js
    const WebpackMerge = require("webpack-merge");
    const path = require('path')
    const Config = require("./webpack.common");
    
    const devServer = {
      port: 8848,
      historyApiFallback: true,
      compress: true, //gzip压缩
      open: true,
      proxy: {
        "/": {},
      },
    };
    
    const devConfig = {
      mode: "development",
      devServer: devServer,
    };
    
    module.exports = WebpackMerge.merge(Config, devConfig);
    
    
    // webpack.prod.js
    const { merge } = require("webpack-merge");
    const commonConfig = require("./webpack.common");
    
    module.exports = merge(commonConfig, {
      mode: "production",
    });
    
    
    // url.js  自己命名修改引入路径
    
    module.exports = {
        outPath: {
            dev: 'dev',
            prod: 'dist',
            test: 'test'
        },
        url: {
            dev: '',
            test: '',
            prod: ''
        }
    }
    

    解决无法识别scss.module.scss

    // types/glovals.d.ts 可以自己命名
    declare module '*.scss';
    

    相关文章

      网友评论

          本文标题:webpack5.0 搭建react+ts框架 亲测~

          本文链接:https://www.haomeiwen.com/subject/tfzavrtx.html