Webpack5入门到原理19:React 脚手架搭建

2024-01-21 18:12

本文主要是介绍Webpack5入门到原理19:React 脚手架搭建,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

开发模式配置

// webpack.dev.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");const getStyleLoaders = (preProcessor) => {return ["style-loader","css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env", // 能解决大多数样式兼容性问题],},},},preProcessor,].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: undefined,filename: "static/js/[name].js",chunkFilename: "static/js/[name].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",},module: {rules: [{oneOf: [{// 用来匹配 .css 结尾的文件test: /\.css$/,// use 数组里面 Loader 执行顺序是从右到左use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024, // 小于10kb的图片会被base64处理},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,plugins: [// "@babel/plugin-transform-runtime", // presets中包含了"react-refresh/babel", // 开启js的HMR功能],},},],},],},plugins: [new ESLintWebpackPlugin({context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),new ReactRefreshWebpackPlugin(), // 解决js的HMR功能运行时全局变量的问题// 将public下面的资源复制到dist目录去(除了index.html)new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),toType: "dir",noErrorOnMissing: true, // 不生成错误globOptions: {// 忽略文件ignore: ["**/index.html"],},info: {// 跳过terser压缩jsminimized: true,},},],}),],optimization: {splitChunks: {chunks: "all",},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".jsx", ".js", ".json"], // 自动补全文件扩展名,让jsx可以使用},devServer: {open: true,host: "localhost",port: 3000,hot: true,compress: true,historyApiFallback: true, // 解决react-router刷新404问题},mode: "development",devtool: "cheap-module-source-map",
};

生产模式配置

// webpack.prod.js
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");const getStyleLoaders = (preProcessor) => {return [MiniCssExtractPlugin.loader,"css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env", // 能解决大多数样式兼容性问题],},},},preProcessor,].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: path.resolve(__dirname, "../dist"),filename: "static/js/[name].[contenthash:10].js",chunkFilename: "static/js/[name].[contenthash:10].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",clean: true,},module: {rules: [{oneOf: [{// 用来匹配 .css 结尾的文件test: /\.css$/,// use 数组里面 Loader 执行顺序是从右到左use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024, // 小于10kb的图片会被base64处理},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,plugins: [// "@babel/plugin-transform-runtime" // presets中包含了],},},],},],},plugins: [new ESLintWebpackPlugin({context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),new MiniCssExtractPlugin({filename: "static/css/[name].[contenthash:10].css",chunkFilename: "static/css/[name].[contenthash:10].chunk.css",}),// 将public下面的资源复制到dist目录去(除了index.html)new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),toType: "dir",noErrorOnMissing: true, // 不生成错误globOptions: {// 忽略文件ignore: ["**/index.html"],},info: {// 跳过terser压缩jsminimized: true,},},],}),],optimization: {// 压缩的操作minimizer: [new CssMinimizerPlugin(),new TerserWebpackPlugin(),new ImageMinimizerPlugin({minimizer: {implementation: ImageMinimizerPlugin.imageminGenerate,options: {plugins: [["gifsicle", { interlaced: true }],["jpegtran", { progressive: true }],["optipng", { optimizationLevel: 5 }],["svgo",{plugins: ["preset-default","prefixIds",{name: "sortAttrs",params: {xmlnsOrder: "alphabetical",},},],},],],},},}),],splitChunks: {chunks: "all",},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".jsx", ".js", ".json"],},mode: "production",devtool: "source-map",
};

其他配置

package.json

{"name": "react-cli","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "npm run dev","dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.dev.js","build": "cross-env NODE_ENV=production webpack --config ./config/webpack.prod.js"},"keywords": [],"author": "","license": "ISC","devDependencies": {"@babel/core": "^7.17.10","@pmmmwh/react-refresh-webpack-plugin": "^0.5.5","babel-loader": "^8.2.5","babel-preset-react-app": "^10.0.1","copy-webpack-plugin": "^10.2.4","cross-env": "^7.0.3","css-loader": "^6.7.1","css-minimizer-webpack-plugin": "^3.4.1","eslint-config-react-app": "^7.0.1","eslint-webpack-plugin": "^3.1.1","html-webpack-plugin": "^5.5.0","image-minimizer-webpack-plugin": "^3.2.3","imagemin": "^8.0.1","imagemin-gifsicle": "^7.0.0","imagemin-jpegtran": "^7.0.0","imagemin-optipng": "^8.0.0","imagemin-svgo": "^10.0.1","less-loader": "^10.2.0","mini-css-extract-plugin": "^2.6.0","postcss-loader": "^6.2.1","postcss-preset-env": "^7.5.0","react-refresh": "^0.13.0","sass-loader": "^12.6.0","style-loader": "^3.3.1","stylus-loader": "^6.2.0","webpack": "^5.72.0","webpack-cli": "^4.9.2","webpack-dev-server": "^4.9.0"},"dependencies": {"antd": "^4.20.2","react": "^18.1.0","react-dom": "^18.1.0","react-router-dom": "^6.3.0"},"browserslist": ["last 2 version", "> 1%", "not dead"]
}

.eslintrc.js

module.exports = {extends: ["react-app"], // 继承 react 官方规则parserOptions: {babelOptions: {presets: [// 解决页面报错问题["babel-preset-react-app", false],"babel-preset-react-app/prod",],},},
};

babel.config.js

module.exports = {// 使用react官方规则presets: ["react-app"],
};

合并开发和生产配置

webpack.config.js

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");// 需要通过 cross-env 定义环境变量
const isProduction = process.env.NODE_ENV === "production";const getStyleLoaders = (preProcessor) => {return [isProduction ? MiniCssExtractPlugin.loader : "style-loader","css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env", // 能解决大多数样式兼容性问题],},},},preProcessor,].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: isProduction ? path.resolve(__dirname, "../dist") : undefined,filename: isProduction? "static/js/[name].[contenthash:10].js": "static/js/[name].js",chunkFilename: isProduction? "static/js/[name].[contenthash:10].chunk.js": "static/js/[name].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",clean: true,},module: {rules: [{oneOf: [{// 用来匹配 .css 结尾的文件test: /\.css$/,// use 数组里面 Loader 执行顺序是从右到左use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024, // 小于10kb的图片会被base64处理},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true, // 开启babel编译缓存cacheCompression: false, // 缓存文件不要压缩plugins: [// "@babel/plugin-transform-runtime",  // presets中包含了!isProduction && "react-refresh/babel",].filter(Boolean),},},],},],},plugins: [new ESLintWebpackPlugin({extensions: [".js", ".jsx"],context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),isProduction &&new MiniCssExtractPlugin({filename: "static/css/[name].[contenthash:10].css",chunkFilename: "static/css/[name].[contenthash:10].chunk.css",}),!isProduction && new ReactRefreshWebpackPlugin(),].filter(Boolean),optimization: {minimize: isProduction,// 压缩的操作minimizer: [// 压缩cssnew CssMinimizerPlugin(),// 压缩jsnew TerserWebpackPlugin(),// 压缩图片new ImageMinimizerPlugin({minimizer: {implementation: ImageMinimizerPlugin.imageminGenerate,options: {plugins: [["gifsicle", { interlaced: true }],["jpegtran", { progressive: true }],["optipng", { optimizationLevel: 5 }],["svgo",{plugins: ["preset-default","prefixIds",{name: "sortAttrs",params: {xmlnsOrder: "alphabetical",},},],},],],},},}),],// 代码分割配置splitChunks: {chunks: "all",// 其他都用默认值},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".jsx", ".js", ".json"],},devServer: {open: true,host: "localhost",port: 3000,hot: true,compress: true,historyApiFallback: true,},mode: isProduction ? "production" : "development",devtool: isProduction ? "source-map" : "cheap-module-source-map",
};

修改运行指令 package.json

{"name": "react-cli","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "npm run dev","dev": "cross-env NODE_ENV=development webpack serve --config ./config/webpack.config.js","build": "cross-env NODE_ENV=production webpack --config ./config/webpack.config.js"},"keywords": [],"author": "","license": "ISC","devDependencies": {"@babel/core": "^7.17.10","@pmmmwh/react-refresh-webpack-plugin": "^0.5.5","babel-loader": "^8.2.5","babel-preset-react-app": "^10.0.1","cross-env": "^7.0.3","css-loader": "^6.7.1","css-minimizer-webpack-plugin": "^3.4.1","eslint-config-react-app": "^7.0.1","eslint-webpack-plugin": "^3.1.1","html-webpack-plugin": "^5.5.0","image-minimizer-webpack-plugin": "^3.2.3","imagemin": "^8.0.1","imagemin-gifsicle": "^7.0.0","imagemin-jpegtran": "^7.0.0","imagemin-optipng": "^8.0.0","imagemin-svgo": "^10.0.1","less-loader": "^10.2.0","mini-css-extract-plugin": "^2.6.0","react-refresh": "^0.13.0","sass-loader": "^12.6.0","style-loader": "^3.3.1","stylus-loader": "^6.2.0","webpack": "^5.72.0","webpack-cli": "^4.9.2","webpack-dev-server": "^4.9.0"},"dependencies": {"react": "^18.1.0","react-dom": "^18.1.0","react-router-dom": "^6.3.0"},"browserslist": ["last 2 version", "> 1%", "not dead"]
}

优化配置

const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserWebpackPlugin = require("terser-webpack-plugin");
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const CopyPlugin = require("copy-webpack-plugin");const isProduction = process.env.NODE_ENV === "production";const getStyleLoaders = (preProcessor) => {return [isProduction ? MiniCssExtractPlugin.loader : "style-loader","css-loader",{loader: "postcss-loader",options: {postcssOptions: {plugins: ["postcss-preset-env",],},},},preProcessor && {loader: preProcessor,options:preProcessor === "less-loader"? {// antd的自定义主题lessOptions: {modifyVars: {// 其他主题色:https://ant.design/docs/react/customize-theme-cn"@primary-color": "#1DA57A", // 全局主色},javascriptEnabled: true,},}: {},},].filter(Boolean);
};module.exports = {entry: "./src/main.js",output: {path: isProduction ? path.resolve(__dirname, "../dist") : undefined,filename: isProduction? "static/js/[name].[contenthash:10].js": "static/js/[name].js",chunkFilename: isProduction? "static/js/[name].[contenthash:10].chunk.js": "static/js/[name].chunk.js",assetModuleFilename: "static/js/[hash:10][ext][query]",clean: true,},module: {rules: [{oneOf: [{test: /\.css$/,use: getStyleLoaders(),},{test: /\.less$/,use: getStyleLoaders("less-loader"),},{test: /\.s[ac]ss$/,use: getStyleLoaders("sass-loader"),},{test: /\.styl$/,use: getStyleLoaders("stylus-loader"),},{test: /\.(png|jpe?g|gif|svg)$/,type: "asset",parser: {dataUrlCondition: {maxSize: 10 * 1024,},},},{test: /\.(ttf|woff2?)$/,type: "asset/resource",},{test: /\.(jsx|js)$/,include: path.resolve(__dirname, "../src"),loader: "babel-loader",options: {cacheDirectory: true,cacheCompression: false,plugins: [// "@babel/plugin-transform-runtime",  // presets中包含了!isProduction && "react-refresh/babel",].filter(Boolean),},},],},],},plugins: [new ESLintWebpackPlugin({extensions: [".js", ".jsx"],context: path.resolve(__dirname, "../src"),exclude: "node_modules",cache: true,cacheLocation: path.resolve(__dirname,"../node_modules/.cache/.eslintcache"),}),new HtmlWebpackPlugin({template: path.resolve(__dirname, "../public/index.html"),}),isProduction &&new MiniCssExtractPlugin({filename: "static/css/[name].[contenthash:10].css",chunkFilename: "static/css/[name].[contenthash:10].chunk.css",}),!isProduction && new ReactRefreshWebpackPlugin(),// 将public下面的资源复制到dist目录去(除了index.html)new CopyPlugin({patterns: [{from: path.resolve(__dirname, "../public"),to: path.resolve(__dirname, "../dist"),toType: "dir",noErrorOnMissing: true, // 不生成错误globOptions: {// 忽略文件ignore: ["**/index.html"],},info: {// 跳过terser压缩jsminimized: true,},},],}),].filter(Boolean),optimization: {minimize: isProduction,// 压缩的操作minimizer: [// 压缩cssnew CssMinimizerPlugin(),// 压缩jsnew TerserWebpackPlugin(),// 压缩图片new ImageMinimizerPlugin({minimizer: {implementation: ImageMinimizerPlugin.imageminGenerate,options: {plugins: [["gifsicle", { interlaced: true }],["jpegtran", { progressive: true }],["optipng", { optimizationLevel: 5 }],["svgo",{plugins: ["preset-default","prefixIds",{name: "sortAttrs",params: {xmlnsOrder: "alphabetical",},},],},],],},},}),],// 代码分割配置splitChunks: {chunks: "all",cacheGroups: {// layouts通常是admin项目的主体布局组件,所有路由组件都要使用的// 可以单独打包,从而复用// 如果项目中没有,请删除layouts: {name: "layouts",test: path.resolve(__dirname, "../src/layouts"),priority: 40,},// 如果项目中使用antd,此时将所有node_modules打包在一起,那么打包输出文件会比较大。// 所以我们将node_modules中比较大的模块单独打包,从而并行加载速度更好// 如果项目中没有,请删除antd: {name: "chunk-antd",test: /[\\/]node_modules[\\/]antd(.*)/,priority: 30,},// 将react相关的库单独打包,减少node_modules的chunk体积。react: {name: "react",test: /[\\/]node_modules[\\/]react(.*)?[\\/]/,chunks: "initial",priority: 20,},libs: {name: "chunk-libs",test: /[\\/]node_modules[\\/]/,priority: 10, // 权重最低,优先考虑前面内容chunks: "initial",},},},runtimeChunk: {name: (entrypoint) => `runtime~${entrypoint.name}`,},},resolve: {extensions: [".jsx", ".js", ".json"],},devServer: {open: true,host: "localhost",port: 3000,hot: true,compress: true,historyApiFallback: true,},mode: isProduction ? "production" : "development",devtool: isProduction ? "source-map" : "cheap-module-source-map",performance: false, // 关闭性能分析,提示速度
};

这篇关于Webpack5入门到原理19:React 脚手架搭建的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/630412

相关文章

部署Vue项目到服务器后404错误的原因及解决方案

《部署Vue项目到服务器后404错误的原因及解决方案》文章介绍了Vue项目部署步骤以及404错误的解决方案,部署步骤包括构建项目、上传文件、配置Web服务器、重启Nginx和访问域名,404错误通常是... 目录一、vue项目部署步骤二、404错误原因及解决方案错误场景原因分析解决方案一、Vue项目部署步骤

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2

CSS弹性布局常用设置方式

《CSS弹性布局常用设置方式》文章总结了CSS布局与样式的常用属性和技巧,包括视口单位、弹性盒子布局、浮动元素、背景和边框样式、文本和阴影效果、溢出隐藏、定位以及背景渐变等,通过这些技巧,可以实现复杂... 一、单位元素vm 1vm 为视口的1%vh 视口高的1%vmin 参照长边vmax 参照长边re

CSS3中使用flex和grid实现等高元素布局的示例代码

《CSS3中使用flex和grid实现等高元素布局的示例代码》:本文主要介绍了使用CSS3中的Flexbox和Grid布局实现等高元素布局的方法,通过简单的两列实现、每行放置3列以及全部代码的展示,展示了这两种布局方式的实现细节和效果,详细内容请阅读本文,希望能对你有所帮助... 过往的实现方法是使用浮动加

css渐变色背景|<gradient示例详解

《css渐变色背景|<gradient示例详解》CSS渐变是一种从一种颜色平滑过渡到另一种颜色的效果,可以作为元素的背景,它包括线性渐变、径向渐变和锥形渐变,本文介绍css渐变色背景|<gradien... 使用渐变色作为背景可以直接将渐China编程变色用作元素的背景,可以看做是一种特殊的背景图片。(是作为背

本地搭建DeepSeek-R1、WebUI的完整过程及访问

《本地搭建DeepSeek-R1、WebUI的完整过程及访问》:本文主要介绍本地搭建DeepSeek-R1、WebUI的完整过程及访问的相关资料,DeepSeek-R1是一个开源的人工智能平台,主... 目录背景       搭建准备基础概念搭建过程访问对话测试总结背景       最近几年,人工智能技术

MySQL中的MVCC底层原理解读

《MySQL中的MVCC底层原理解读》本文详细介绍了MySQL中的多版本并发控制(MVCC)机制,包括版本链、ReadView以及在不同事务隔离级别下MVCC的工作原理,通过一个具体的示例演示了在可重... 目录简介ReadView版本链演示过程总结简介MVCC(Multi-Version Concurr

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...

css实现图片旋转功能

《css实现图片旋转功能》:本文主要介绍了四种CSS变换效果:图片旋转90度、水平翻转、垂直翻转,并附带了相应的代码示例,详细内容请阅读本文,希望能对你有所帮助... 一 css实现图片旋转90度.icon{ -moz-transform:rotate(-90deg); -webkit-transfo

vue基于ElementUI动态设置表格高度的3种方法

《vue基于ElementUI动态设置表格高度的3种方法》ElementUI+vue动态设置表格高度的几种方法,抛砖引玉,还有其它方法动态设置表格高度,大家可以开动脑筋... 方法一、css + js的形式这个方法需要在表格外层设置一个div,原理是将表格的高度设置成外层div的高度,所以外层的div需要