使用webpack搭建react项目

初始化项目空间

新建一个项目目录,在目录下执行:npm init -y
此时将会生成 package.json 文件
之后新建 src、config(配置webpack)文件夹,新建index.html文件

安装依赖文件

npm i webpack webpack-cli webpack-dev-server html-webpack-plugin babel-loader path -D
npm i react react-dom react-router-dom

在src目录配置index.js文件

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <React.StrictMode>
    <div>你好,React-webpack5-template</div>
  </React.StrictMode>,
  document.getElementById('root')
);

在src目录配置index.html文件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>react-app</title>
  </head>
  <body>
    <div id="app"></div>
  </body>
</html>


配置config中webpack配置文件

1、新建webpack.base.conf.js文件,部分代码仅供参考

"use strict";
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  // 入口起点
  entry: {
    app: "./src/index.js",
  },
  // 输出
  output: {
    path: path.resolve(__dirname, "../dist"),
    filename: "[name].js",
  },
  // 解析
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"],
    alias: {
      "@components": path.join(__dirname, "../src/components"),
      "@utils": path.join(__dirname, "../src/utils"),
      "@pages": path.join(__dirname, "../src/pages"),
    },
  },
  // loader
  module: {
    rules: [
      {
        test: /\.js|jsx$/,
        exclude: /(node_modules|bower_components)/, // 屏蔽不需要处理的文件(文件夹)(可选)    
        use: {
          loader: "babel-loader", // 使用babel-loader处理js文件
          options: {
            presets: ["@babel/preset-env", "@babel/preset-react"], // 使用babel预设处理ES6和React语法
          },
        },
      },
      {
        //支持less
        // npm install style-loader css-loader less-loader less --save-dev
        test: /\.(le|c)ss$/, // .less and .css
        use: ["style-loader", "css-loader", "less-loader"], // 创建的css文件存在html的头部
      },
    ],
  },
  // 插件
  plugins: [
    new HtmlWebpackPlugin({
      filename: "index.html",
      template: "src/index.html",
      inject: "body",
      hash: false,
      minify: {
        collapseWhitespace: true, //把生成文件的内容的没用空格去掉,减少空间
      },
    }),
  ],
};

2、新建用于开发环境的webpack.dev.conf.js 文件

"use strict";
const { merge } = require("webpack-merge");
const baseWebpackConfig = require("./webpack.base.conf");
const path = require("path");
const webpack = require("webpack");

module.exports = merge(baseWebpackConfig, {
  // 模式
  mode: "development",
  // 调试工具
  devtool: "inline-source-map",
  // 开发服务器
  devServer: {
    static: path.resolve(__dirname, "static"),
    historyApiFallback: true, // 在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html
    compress: true, // 启用gzip压缩
    hot: true, // 模块热更新,取决于HotModuleReplacementPlugin
    host: "127.0.0.1", // 设置默认监听域名,如果省略,默认为“localhost”
    port: 8888, // 设置默认监听端口,如果省略,默认为“8080”
  },
  optimization: {
    nodeEnv: "development",
  },
});

3、新建webpack.prod.conf.js文件

"use strict";
const { merge } = require("webpack-merge");
const baseWebpackConfig = require("./webpack.base.conf");

const path = require("path");
const webpack = require("webpack");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = merge(baseWebpackConfig, {
  // 模式
  mode: "production",
  // 调试工具
  devtool: "source-map",
  // 输出
  output: {
    path: path.resolve(__dirname, "../dist"),
    filename: "js/[name].[chunkhash].js",
  },
  // 插件
  plugins: [new CleanWebpackPlugin()],
  // 代码分离相关
  optimization: {
    nodeEnv: "production",
    runtimeChunk: {
      name: "manifest",
    },
    splitChunks: {
      minSize: 30000,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      name: false,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendor",
          chunks: "initial",
        },
      },
    },
  },
});

新建.babelrc文件

{
  "presets": ["latest", "react", "stage-2"],
  "plugins": []
}

修改package.json中的script代码

  "scripts": {
    "dev": "webpack-dev-server --hot  --config config/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "webpack --progress --colors --config config/webpack.prod.conf.js"
  },

此时,package.json中部分代码如下

{
  "name": "webpack-react-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --hot  --config config/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "webpack --progress  --config config/webpack.prod.conf.js"
  },
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.5",
    "babel-plugin-import": "^1.13.5",
    "babel-preset-latest": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "clean-webpack-plugin": "^4.0.0",
    "css-loader": "^6.7.1",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.5.0",
    "less-loader": "^11.0.0",
    "node-less": "^1.0.0",
    "style-loader": "^3.3.1",
    "url-loader": "^4.1.1",
    "webpack": "^5.74.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.10.1",
    "webpack-merge": "^5.8.0"
  },
  "dependencies": {
    "less": "^4.1.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^5.1.2"
  }
}

在项目中添加代码规范检测

yarn add babel-eslint --save-dev
yarn add @umijs/fabric -D   //@umijs/fabric一个包含 prettier,eslint,stylelint 的配置文件合集。
yarn add prettier --save-dev  //默认@umijs/fabric已经给我们安装了需要的依赖,但是默认是没有pretter。

新增如下文件

1、.eslintrc.js文件

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [require.resolve("@umijs/fabric/dist/eslint")],
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 12,
    sourceType: "module",
  },
  parser: "babel-eslint",
  globals: {
    gtag: true,
    $: true,
    _g_deflang: true,
    require: true,
    envConfig: true,
    process: true,
    React: true,
    ysf: true,
    initNECaptcha: true,
    initNECaptchaWithFallback: true,
  },
  // plugins: ["react"],
  rules: {
    //"react/jsx-uses-react": 2,
    "no-nested-ternary": 0, // 允许嵌套三元表达式
    "no-script-url": 0, // 允许javascript:;
    "prefer-destructuring": 0, // 关闭强制使用解构
    "no-plusplus": 0, // 允许使用++和--的操作
    "array-callback-return": 0, // 允许数组map不返回值
    "consistent-return": 0,
    "no-param-reassign": 0, // 允许修改函数形参
    "no-unused-expressions": 0,
    "no-restricted-syntax": 0,
    "react/prop-types": 0,
    "no-prototype-builtins": 0,
    "react/no-deprecated": 0, // 关闭react弃用检测
    "react/no-string-refs": 0,
    "no-useless-escape": 0,
  },
};

2、.eslintignore文件

/lambda/
/scripts/*
.history
serviceWorker.ts
/config/*
/public/*
*.js

3、.prettierrc.js文件

module.exports = {
  singleQuote: true,
  jsxSingleQuote: true,
  semi: true,
};

4、.prettierignore文件

**/*.svg
package.json
.umi
.umi-production
/dist
.dockerignore
.DS_Store
.eslintignore
*.png
*.toml
docker
.editorconfig
Dockerfile*
.gitignore
.prettierignore
LICENSE
.eslintcache
*.lock
yarn-error.log
.history

5、.stylelintrc.js文件

const fabric = require('@umijs/fabric');
module.exports = {
  ...fabric.stylelint,
};

替换package.json中命令

  "scripts": {
    "lint": "umi g tmp && npm run lint:js && npm run lint:style && npm run lint:prettier",
    "lint-staged:js": "eslint --ext .js,.jsx,.ts,.tsx ",
    "lint:fix": "eslint --fix --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src && npm run lint:style",
    "lint:js": "eslint --cache --ext .js,.jsx,.ts,.tsx --format=pretty ./src",
    "lint:prettier": "prettier --check \"src/**/*\" --end-of-line auto",
    "lint:style": "stylelint --fix \"src/**/*.less\" --syntax less",
    "prettier": "prettier -c --write \"src/**/*\"",
    "precommit": "lint-staged",
    "precommit:fix": "npm run lint:fix && npm run prettier && npm run lint:prettier && npm run lint:style",
    "dev": "webpack-dev-server --hot  --config config/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "webpack --progress  --config config/webpack.prod.conf.js"
  },

添加提交前检测

#使用husky lint-staged在commit的时候校检你提交的代码是否符合规范
yarn add husky lint-staged -D

package.json新增如下代码:

  "lint-staged": {
    "**/*.less": "stylelint--syntaxless",
    "**/*.{js,jsx,ts,tsx}": "npmrunlint-staged:js",
    "**/*.{js,jsx,tsx,ts,less,md,json}": [
      "prettier--write"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "npmrunlint-staged"
    }
  }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,首先你需要安装webpack5、react、typescript、eslint以及相关的loader和插件。你可以通过以下命令安装它们: ``` npm install webpack webpack-cli webpack-dev-server react react-dom @types/react @types/react-dom typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks prettier -D ``` 接下来,你需要创建一个webpack配置文件,可以命名为`webpack.config.js`,在该文件中配置webpack相关内容: ```javascript const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.tsx', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.(ts|tsx)$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', ], }, }, { loader: 'ts-loader', }, ], }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', }), ], devtool: 'inline-source-map', devServer: { contentBase: './dist', port: 3000, }, mode: 'development', }; ``` 在上面的配置中,我们指定了入口文件为`src/index.tsx`,打包后的输出文件为`dist/bundle.js`。我们还通过resolve属性指定了文件的拓展名,这样在引入文件时就不用指定拓展名了。 在module属性中,我们定义了不同类型文件的loader,例如对于`.tsx`和`.ts`文件,我们使用了`babel-loader`和`ts-loader`,对于`.js`和`.jsx`文件,我们只使用了`babel-loader`。此外,我们还使用了`style-loader`和`css-loader`处理`.css`文件。 在plugins属性中,我们使用了`HtmlWebpackPlugin`插件,用于生成HTML文件。在devServer属性中,我们指定了开发服务器的端口和从哪个文件夹提供内容。 最后,我们使用了`inline-source-map`作为开发模式下的source-map,将模式设置为`development`。 接下来,你需要创建一个`.babelrc`文件,用于配置babel: ```json { "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"] } ``` 然后,你需要创建一个`.eslintrc.json`文件,用于配置eslint: ```json { "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "extends": ["airbnb", "plugin:@typescript-eslint/recommended", "prettier"], "rules": { "prettier/prettier": ["error"], "react/jsx-filename-extension": [1, { "extensions": [".tsx"] }], "import/extensions": ["error", "never", { "svg": "always" }] }, "settings": { "import/resolver": { "node": { "extensions": [".js", ".jsx", ".ts", ".tsx"] } } } } ``` 在上面的配置中,我们使用了`@typescript-eslint/parser`解析Typescript代码,并使用了`@typescript-eslint/eslint-plugin`插件提供的规则。我们还继承了`eslint-config-airbnb`和`eslint-config-prettier`,并使用了一些自定义的规则。 最后,你需要在`package.json`中添加一些scripts,用于启动开发服务器和打包代码: ```json { "scripts": { "start": "webpack serve --mode development", "build": "webpack --mode production" } } ``` 现在你就可以使用`npm start`命令启动开发服务器,使用`npm run build`命令打包代码了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值