尚硅谷 React脚手架
其他配置
- page.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官方规则,已内置core-js用于语法兼容
presets: ["react-app"],
};
开发模式配置
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ReactRefreshWebpackPlugin = require("@pmmmwh/react-refresh-webpack-plugin"); // react用于js热替换功能的插件
const CopyPlugin = require("copy-webpack-plugin");
/**
*
* @param {String} preProcessor 预处理loader
* @returns loder数组
*/
const getStyleLoaders = (preProcessor) => {
return [
"style-loader",
"css-loader",
// css兼容处理
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
"postcss-preset-env", // 能解决大多数样式兼容性问题
],
},
},
},
preProcessor
].filter(Boolean)
}
module.expoets = {
// 入口文件
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]" // assets资源文件名
},
module: {
rules: [
{
// 防止匹配成功后再向下匹配
oneOf: [
{
// 用来匹配 .css 结尾的文件
test: /\.css$/,
// use 数组里面 Loader 执行顺序是从右到左
use: getStyleLoaders(),
},
{
// 用来匹配 .less结尾的文件
test: /\.less$/,
use: getStyleLoaders("less-loader"),
},
{
// 用来匹配 .sass或.scss结尾的文件
test: /\.s[ac]ss$/,
use: getStyleLoaders("sass-loader"),
},
{
// 用来匹配 .sty结尾的文件
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",
}, {
// 用于匹配 .js或.jsx结尾的文件
test: /\.(jsx|js)$/,
include: path.resolve(__dirname, "../src"), // 该loader只处理 根目录下的src文件下的所有js文件
loader: "babel-loader",
options: {
cacheDirectory: true, // 开启缓存
cacheCompression: false, // 关闭缓存文件压缩,为了增加速度
plugins: [
// "@babel/plugin-transform-runtime", // presets中包含了
"react-refresh/babel", // 开启js的HMR功能
],
},
}
]
}
]
},
plugins: [
// ESLint
new ESLintWebpackPlugin({
context: path.resolve(__dirname, "../src"), // 该plugin检查 根目录下的src文件下的所有js文件
exclude: "node_modules", // 排除node_modules文件夹
cache: true, // 开启缓存
cacheLocation: path.resolve( // 缓存目录(缓存到哪个文件中)
__dirname,
"../node_modules/.cache/.eslintcache"
),
}),
// 自动生成html打包文件,自动导入资源(防止因文件hash值的改变影响文件的引入)
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压缩js
minimized: true,
},
},
],
}),
],
mode: 'development',
devtool: "cheap-module-source-map", // 开启SourceMap——代码映射
// optimization,中文翻译:优化
optimization: {
// 代码分割
splitChunks: {
chunks: "all",
},
// 保管hash值,减少文件更新
runtimeChunk: {
name: (entrypoint) => `runtime~${entrypoint.name}`,
},
},
// webpack解析模块加载选项
resolve: {
// 自动补全文件扩展名
// 当引入的文件没有文件扩展名,首先会以.jsx文件进行解析,如果不行,则使用.js,再不行则使用.json,以此类推
// 当一个匹配完成就不会继续匹配
extensions: [".jsx", ".js", ".json"]
},
devServer: {
open: true, // 是否自动打开浏览器
host: "localhost",
port: 3000,
hot: true, // 开启热模块替换
compress: true,
historyApiFallback: true, // 解决react-router刷新404问题,当我们访问3000/home,会显示404,因为我们只有一个index.html文件,需要返回index.html中寻找
}
}
生产模式模式
const path = require("path");
const ESLintWebpackPlugin = require("eslint-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin") // 提取css单独文件
const TerserWebpackPlugin = require("terser-webpack-plugin"); // js压缩
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin"); // css压缩
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin"); // 图片压缩
const CopyPlugin = require("copy-webpack-plugin");
/**
*
* @param {String} preProcessor 预处理loader
* @returns loder数组
*/
const getStyleLoaders = (preProcessor) => {
return [
MiniCssExtractPlugin.loader,
"css-loader",
// css兼容处理
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [
"postcss-preset-env", // 能解决大多数样式兼容性问题
],
},
},
},
preProcessor
].filter(Boolean)
}
module.expoets = {
// 入口文件
entry: "./src/main/js",
output: {
path: path.resolve(__dirname, "../dist"),
filename: "static/js/[name].[contenthash:10].js", // 添加hash方便保存
chunkFilename: 'static/js/[name].chunk.[contenthash:10].js',
assetModuleFilename: "static/js/[hash:10][ext][query]", // assets资源文件名
clean: true
},
module: {
rules: [
{
// 防止匹配成功后再向下匹配
oneOf: [
{
// 用来匹配 .css 结尾的文件
test: /\.css$/,
// use 数组里面 Loader 执行顺序是从右到左
use: getStyleLoaders(),
},
{
// 用来匹配 .less结尾的文件
test: /\.less$/,
use: getStyleLoaders("less-loader"),
},
{
// 用来匹配 .sass或.scss结尾的文件
test: /\.s[ac]ss$/,
use: getStyleLoaders("sass-loader"),
},
{
// 用来匹配 .sty结尾的文件
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",
}, {
// 用于匹配 .js或.jsx结尾的文件
test: /\.(jsx|js)$/,
include: path.resolve(__dirname, "../src"), // 该loader只处理 根目录下的src文件下的所有js文件
loader: "babel-loader",
options: {
cacheDirectory: true, // 开启缓存
cacheCompression: false, // 关闭缓存文件压缩,为了增加速度
},
}
]
}
]
},
plugins: [
// ESLint
new ESLintWebpackPlugin({
context: path.resolve(__dirname, "../src"), // 该plugin检查 根目录下的src文件下的所有js文件
exclude: "node_modules", // 排除node_modules文件夹
cache: true, // 开启缓存
cacheLocation: path.resolve( // 缓存目录(缓存到哪个文件中)
__dirname,
"../node_modules/.cache/.eslintcache"
),
}),
// 自动生成html打包文件,自动导入资源(防止因文件hash值的改变影响文件的引入)
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "../public/index.html"), // 内容模板路径
}),
new MiniCssExtractPlugin({
// css文件名称
filename: 'static/css/[name].[contenthash:10].css',
// chunk文件的命名
chunkFilename: 'static/css/[name].[contenthash:10].chunk.css',
}),
// 将public下面的资源复制到dist目录去(除了index.html),因为public文件下的文件除了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压缩js
minimized: true,
},
},
],
}),
],
mode: 'production',
devtool: "cheap-module-source-map", // 开启SourceMap——代码映射
// optimization,中文翻译:优化
optimization: {
// 代码分割
splitChunks: {
chunks: "all",
},
// 保管hash值,减少文件更新
runtimeChunk: {
name: (entrypoint) => `runtime~${entrypoint.name}`,
},
// 压缩
minimizer: [
new TerserWebpackPlugin(), // js压缩
new CssMinimizerPlugin(), // css压缩
// 图片压缩
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",
},
},
],
},
],
],
},
},
}),
]
},
// webpack解析模块加载选项
resolve: {
// 自动补全文件扩展名
// 当引入的文件没有文件扩展名,首先会以.jsx文件进行解析,如果不行,则使用.js,再不行则使用.json,以此类推
// 当一个匹配完成就不会继续匹配
extensions: [".jsx", ".js", ".json"]
}
}
合并开发和生产配置
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: [
// 压缩css
new CssMinimizerPlugin(),
// 压缩js
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"],
},
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",
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。