在這篇文章中,我們將介紹設定可部署的 React 應用程式所需了解的所有資訊。

GitHub 儲存庫:https://github.com/shivam-pawar/sample-react-app

先決條件

在開始之前,請確保您的電腦上安裝了 Node.js 和 npm(或yarn)。

初始化一個新專案

使用命令列並導航到專案的根資料夾並輸入

npm init

這將詢問您一些基本訊息,例如軟體包名稱、作者姓名、描述和許可證。有了這些訊息,它將建立一個名為package.json 的文件

安裝 React 和 TypeScript

  • 安裝 React 和 ReactDOM 作為相依性:
npm install react react-dom
  • 安裝 TypeScript 及其類型作為開發依賴項:
npm install --save-dev typescript @types/react @types/react-dom

設定 Webpack

安裝必要的 Webpack 相依性:

npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin webpack-merge ts-loader terser-webpack-plugin uglify-js

你的package.json看起來像這樣:

包.json

  • 在根/專案層級建立一個webpack資料夾,並在其中新增這 3 個設定檔。
  1. webpack.common.js

  2. webpack.config.js

  3. webpack.dev.js

  4. webpack.prod.js

  • 在根/專案層級建立一個src資料夾,並在其中新增這兩個檔案。
  1. 索引.tsx

  2. 索引.html

  • 將以下程式碼複製並貼上到index.tsx
import React from "react";
import { createRoot } from "react-dom/client";

const App = () => {
  return <div>Hello, React!</div>;
};

const rootElement = document.getElementById("root") as Element;
const root = createRoot(rootElement);

root.render(<App />);

  • 將以下程式碼複製並貼上到index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My React App</title>
</head>
<body>
  <div id="root"></div>
</body>
</html>

現在讓我們更新 webpack 設定檔。

  • webpack.common.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: path.resolve(__dirname, "..", "./src/index.tsx"),
  output: {
    path: path.resolve(__dirname, "..", "dist"),
    filename: "bundle.js",
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"],
  },
  module: {
    rules: [
      {
        test: /\.(ts|js)x?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, "..", "./src/index.html"),
    }),
  ],
  devServer: {
    static: "./dist",
  },
};

  • webpack.config.js
const { merge } = require("webpack-merge");
const commonConfig = require("./webpack.common");

module.exports = (envVars) => {
  const { env } = envVars;
  const envConfig = require(`./webpack.${env}.js`);
  const config = merge(commonConfig, envConfig);
  return config;
};

  • webpack.dev.js
const webpack = require("webpack");

module.exports = {
  mode: "development",
  devtool: "cheap-module-source-map",
  devServer: {
    hot: true,
    open: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env.name": JSON.stringify("development"),
    }),
  ],
};

  • webpack.prod.js
const webpack = require("webpack");
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
  mode: "production",
  devtool: false,
  plugins: [
    new webpack.DefinePlugin({
      "process.env.name": JSON.stringify("production"),
    }),
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new TerserPlugin({
        minify: TerserPlugin.uglifyJsMinify,
        extractComments: true,
        parallel: true,
        test: /\.(ts|js)x?$/,
        terserOptions: {
          compress: {
            drop_console: true,
          },
          output: {
            comments: false,
          },
        },
      }),
    ],
  },
};
  • 更新/替換package.json檔案中的腳本部分:
"scripts": {
    "start": "webpack serve --config webpack/webpack.config.js --env env=dev",
    "build": "webpack --config webpack/webpack.config.js --env env=prod"
  }

設定打字稿

在根/專案層級新增tsconfig.json檔案並將以下配置貼到其中。

{
  "compilerOptions": {
    "target": "ES6",                                  
    "lib": [
      "DOM",
      "ESNext"
    ],                                        
    "jsx": "react-jsx",                               
    "module": "ESNext",                               
    "moduleResolution": "Node",                     
    "types": ["react", "react-dom", "@types/react", "@types/react-dom"],                                      
    "resolveJsonModule": true,                       
    "isolatedModules": true,                          
    "esModuleInterop": true,                            
    "forceConsistentCasingInFileNames": true,            
    "strict": true,                                      
    "skipLibCheck": true                                
  }
}

現在您的專案資料夾和文件結構將如下所示:

專案結構

執行開發伺服器

在終端機/命令提示字元中執行以下命令來執行您的開發伺服器:

npm start

您的 React 應用程式現在應該在http://localhost:8080上執行。

設定 ESLint 和 Prettier

  • 安裝 ESLint、Prettier 和必要的插件:
npm install --save-dev eslint eslint-config-prettier eslint-plugin-prettier @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-react
  • 使用以下配置在專案的根目錄中建立.eslintrc.json檔案:
{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": [
    "react",
    "@typescript-eslint",
    "prettier"
  ],
  "rules": {
    "prettier/prettier": "error"
  }
}
  • 使用以下配置在專案的根目錄中建立一個.prettierrc檔案:
{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": false,
  "printWidth": 100,
  "tabWidth": 2
}
  • 更新package.json檔案中的腳本部分:
"scripts": {
    "start": "webpack serve --config webpack/webpack.config.js --env env=dev",
    "build": "webpack --config webpack/webpack.config.js --env env=prod",
    "lint": "eslint . --ext .ts,.tsx --fix"
  }
  • 執行 ESLint 以檢查是否有任何 linting 問題:
npm run lint

最終的package.json將如下所示:

最終的package.json

您的最終資料夾結構將如下所示:

最終資料夾結構

結論

透過遵循本指南,您現在已經擁有了一個使用 Webpack、TypeScript、ESLint 和 Prettier 進行生產的 React 應用程式設定。此設定為建立具有最佳實踐的可擴展且可維護的 React 應用程式提供了堅實的基礎。

請記住使您的依賴項保持最新,並繼續學習這些工具以進一步優化您的開發工作流程。

快樂編碼!

如果您覺得這篇文章有用,請分享給您的朋友和同事!

閱讀更多關於 Dev.To ➡️ Shivam Pawar 的文章

關注我⤵️

🌐領英

🌐Github


原文出處:https://dev.to/shivampawar/optimizing-your-react-app-a-guide-to-production-ready-setup-with-webpack-typescript-eslint-and-prettier-2024-4lcl


共有 0 則留言