优化你的 React 应用:使用 Webpack、TypeScript、ESLint 和 Prettier 进行生产环境配置的指南 - 2024
在这篇博文中,我们将介绍设置可供部署的 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将如下所示:
-
在根/项目级别创建一个webpack文件夹,并在其中添加这 3 个配置文件。
- webpack.common.js
- webpack.config.js
- webpack.dev.js
- webpack.prod.js
-
在根/项目级别创建一个src文件夹,并在其中添加这两个文件。
- 索引.tsx
- 索引.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"
}
设置 TypeScript
在根/项目级别添加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将如下所示:
您的最终文件夹结构将如下所示:
结论
按照本指南操作,您现在已拥有一个包含 Webpack、TypeScript、ESLint 和 Prettier 的、可用于生产的 React 应用程序。此设置将为构建可扩展且可维护的 React 应用程序奠定坚实的基础,并遵循最佳实践。
请记住保持依赖项的更新,并继续学习这些工具以进一步优化您的开发工作流程。
祝您编码愉快!❤️
如果您发现这篇文章有用,请与您的朋友和同事分享!
阅读更多关于 Dev.To 的文章 ➡️ Shivam Pawar
文章来源:https://dev.to/shivampawar/optimizing-your-react-app-a-guide-to-production-ready-setup-with-webpack-typescript-eslint-and-prettier-2024-4lcl