news 2026/8/10 17:21:17

现代webpack/react/typescript/pnpm项目模板,从零到一搭建webpack项目

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
现代webpack/react/typescript/pnpm项目模板,从零到一搭建webpack项目

项目模板

模板地址
如果急用,直接使用当前模板即可。点击右上角Use This Template即可创建一个新的项目。

背景

当我每每创建一个新的webpack项目时,总是需要经过繁琐的webpack配置来完成项目的init。如果从网络上搜寻快速的setup总会遇到各种各样的问题(由于包的版本有更新,有些配置已经废弃掉了)所有我决定搭建自己的webpack配置模板。

搭建步骤

1. pnpm 开启webpack项目

1.1 生成package.json

pnpminit

1.2 引入webpack

pnpmadd-D webpack webpack-cli webpack-dev-server

1.3 引入typescript

pnpmadd-D typescript ts-node @types/node

1.4 引入react

pnpmaddreact react-dom
pnpmadd-D @types/react @types/react-dom

2. 初始化react代码

2.1 创建src/app.tsx

constApp=()=>{return<div>Hello World</div>}exportdefaultApp

2.2 创建src/index.tsx

import{createRoot}from'react-dom/client'importAppfrom'./app'createRoot(document.getElementById('root')!).render(<App/>)

3. webpack配置

3.1 创建webpack.config.ts

importpathfrom'path'import{fileURLToPath}from'url'importtype{Configuration}from'webpack'constrootDir=path.dirname(fileURLToPath(import.meta.url))constconfig:Configuration={entry:'./src/index.tsx',output:{path:path.resolve(rootDir,'dist'),filename:'[name].[contenthash].js'},resolve:{extensions:['.ts','.tsx','.js','.jsx']},devtool:'source-map',module:{},mode:'development'}exportdefaultconfig

3.2 设置webpack插件

pnpmadd-D html-webpack-plugin clean-webpack-plugin

在public下创建index.html

<!doctypehtml><htmllang="en"><head><metacharset="UTF-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><title>Webpack React Template</title></head><body><divid="root"></div></body></html>

webpack 补充插件配置以及devServer配置

importpathfrom'path'import{fileURLToPath}from'url'importHtmlWebpackPluginfrom'html-webpack-plugin'import{CleanWebpackPlugin}from'clean-webpack-plugin'importtype{Configuration}from'webpack'import'webpack-dev-server'constrootDir=path.dirname(fileURLToPath(import.meta.url))constconfig:Configuration={entry:'./src/index.tsx',output:{path:path.resolve(rootDir,'dist'),filename:'[name].[contenthash].js'},resolve:{extensions:['.ts','.tsx','.js','.jsx']},plugins:[newHtmlWebpackPlugin({template:'./public/index.html'}),newCleanWebpackPlugin()],devtool:'source-map',devServer:{static:{directory:path.join(rootDir,'public')},compress:true,historyApiFallback:true},mode:'development'}exportdefaultconfig

3.3 设置webpack loader(style)

pnpmadd-D style-loader css-loader sass sass-loader

引入到webpack config的rules中:

constconfig:Configuration={entry:'./src/index.tsx',output:{path:path.resolve(rootDir,'dist'),filename:'[name].[contenthash].js'},resolve:{extensions:['.ts','.tsx','.js','.jsx']},plugins:[newHtmlWebpackPlugin({template:'./public/index.html'}),newCleanWebpackPlugin()],devtool:'source-map',module:{rules:[{test:/\.css$/i,use:['style-loader','css-loader']},{test:/\.scss$/i,use:['style-loader','css-loader','sass-loader']},{test:/\.(png|jpg|jpeg|gif|svg)$/i,type:'asset/resource'}]},devServer:{static:{directory:path.join(rootDir,'public')},compress:true,historyApiFallback:true},mode:'development'}exportdefaultconfig

这里还引入静态资源的rules直接从asset/resource中获取。
因为我们引入了sass,这里我们还需要定义sass文件(.sass,.scss)的模块类型,在src/types里创建index.d.ts:

declaremodule'*.scss'{constcontent:{[className:string]:string}exportdefaultcontent}

3.4 设置webpack babel

pnpmadd-D @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript babel-loader

在config进行如下配置

importpathfrom'path'import{fileURLToPath}from'url'importHtmlWebpackPluginfrom'html-webpack-plugin'import{CleanWebpackPlugin}from'clean-webpack-plugin'importtype{Configuration}from'webpack'import'webpack-dev-server'constrootDir=path.dirname(fileURLToPath(import.meta.url))constconfig:Configuration={entry:'./src/index.tsx',output:{path:path.resolve(rootDir,'dist'),filename:'[name].[contenthash].js'},resolve:{extensions:['.ts','.tsx','.js','.jsx']},plugins:[newHtmlWebpackPlugin({template:'./public/index.html'}),newCleanWebpackPlugin()],devtool:'source-map',module:{rules:[{test:/\.(ts|js)x?$/,exclude:/node_modules/,use:[{loader:'babel-loader',options:{presets:['@babel/preset-env',['@babel/preset-react',{runtime:'automatic'}],'@babel/preset-typescript']}}]},{test:/\.css$/i,use:['style-loader','css-loader']},{test:/\.scss$/i,use:['style-loader','css-loader','sass-loader']},{test:/\.(png|jpg|jpeg|gif|svg)$/i,type:'asset/resource'}]},devServer:{static:{directory:path.join(rootDir,'public')},compress:true,historyApiFallback:true},mode:'development'}exportdefaultconfig

4. typescript配置

根目录上创建tsconfg.json

{"compilerOptions":{"module":"esnext","target":"esnext","moduleResolution":"bundler","lib":["dom","dom.iterable","esnext"],"sourceMap":true,"declaration":true,"declarationMap":true,"noUncheckedIndexedAccess":true,"exactOptionalPropertyTypes":true,"strict":true,"jsx":"react-jsx","jsxImportSource":"react","verbatimModuleSyntax":true,"isolatedModules":true,"noUncheckedSideEffectImports":true,"moduleDetection":"force","skipLibCheck":true}}

通过上述配置,我们修改package.json的scripts

"scripts":{"start":"webpack serve --open --port 3210","build":"webpack"}

此时运行pnpm run start即可在3210端口访问项目。

接下来的内容是锦上添花:优化工程,即代码风格格式化,typescript eslint规则校验,使用git hooks触发生命周期钩子

5. 使用prettier格式化代码

pnpmadd-D prettier

在根目录创建.prettierrc

{"semi":false,"singleQuote":true,"trailingComma":"none","tabWidth":4,"useTabs":false,"printWidth":120,"bracketSpacing":true,"arrowParens":"avoid","endOfLine":"auto"}

在package.json配置格式化脚本

"scripts":{"start":"webpack serve --open --port 3210","build":"webpack","format":"prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\""},

执行即可把src中所有代码文件格式化

6. 配置eslint

pnpmadd-D eslint typescript-eslint eslint-plugin-react eslint-plugin-react-hooks eslint-webpack-plugin

根目录创建eslint.config.js

importtseslintfrom'typescript-eslint'importreactPluginfrom'eslint-plugin-react'importreactHooksfrom'eslint-plugin-react-hooks'exportdefault[...tseslint.configs.recommended,{files:['**/*.{ts,tsx}'],plugins:{react:reactPlugin,'react-hooks':reactHooks},rules:{...reactPlugin.configs.recommended.rules,...reactHooks.configs.recommended.rules},settings:{react:{version:'detect'}}}]

在packages的scripts脚本中写入

"scripts":{"start":"webpack serve --open --port 3210","build":"webpack","format":"prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,md}\"","lint":"eslint --ext .ts,.tsx","lint:fix":"eslint --ext .ts,.tsx --fix"},

7. husky 设置lint-staged

pnpmadd-D husky lint-staged

7.1 初始化git仓库

gitinit

7.2 初始化husky

  1. npx方式
npx husky init
  1. pnpm方式
pnpmexechusky init

7.3 配置husky的pre-commit钩子

在.husky中创建pre-commit(无后缀)文件
写入

npx lint-staged

并在package.json中的根object里写入lint-staged配置

"lint-staged":{"src/**/*.{ts,tsx}":["eslint --fix"]}

此时,每当你git commit的时候它都会先执行eslint

8. husky设置commit message

为了规范每次提交记录的message,我们使用commitlint规范:

feat: add new feature fix: bug fix docs: documentation changes style: formatting changes refactor: code refactoring test: adding tests chore: maintenance tasks

引入commit-lint

pnpmadd-D @commitlint/cli @commitlint/config-conventional

创建commitlint.config.js

exportdefault{extends:['@commitlint/config-conventional']}

在.husky目录中创建commit-msg(无后缀)文件并写入:

pnpmexeccommitlint --edit$1

此后后续的commit提交的message都会匹配是否以上述规范中的lint的title相匹配,比如我提交一个需求必须以:feat:开头

9. 创建.gitignore

屏蔽掉常见的本地配置/依赖项

# Dependencies node_modules .pnpm-store # Build output dist # IDE .idea .vscode *.swp *.swo # OS .DS_Store Thumbs.db # Logs *.log npm-debug.log* # Environment .env .env.local .env.*.local
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/8/10 3:45:57

第8篇 | 流量的“密语”:网络监听与中间人攻击的全景解析

《网络安全的攻防启示录》 第一篇章:破壁之术 第8篇 “你以为你在跟服务器说悄悄话,其实全世界都在听广播。” 想象这样一个场景:周末的午后,你坐在星巴克里,连上了店里的免费 Wi-Fi,点了一杯拿铁,顺手打开手机银行给房东转了房租,又登录公司邮箱回了几封紧急邮件。一…

作者头像 李华
网站建设 2026/8/9 10:44:03

技术升职加薪路上总卡点怎么办?

在职场和技术成长的路上&#xff0c;你是否遇到这些困扰&#xff1a; 想去海外发展&#xff0c;却不知道机会与挑战如何权衡团队里有“技术刺头”&#xff0c;管理难度大测试架构设计一头雾水&#xff0c;不知道从哪个维度下手算法测试、质量大盘建设等知识多但不知如何落地学…

作者头像 李华
网站建设 2026/8/9 9:47:02

CSS伪类及伪元素:一篇搞懂

文章目录一、 伪类&#xff08;Pseudo-classes&#xff09;1.链接伪类2.用户行为伪类3.结构伪类选择器4.表单伪类二、伪元素&#xff08;Pseudo-elements&#xff09;三、核心区别一、 伪类&#xff08;Pseudo-classes&#xff09; 伪类用于选择处于特定状态的元素&#xff0c…

作者头像 李华
网站建设 2026/8/10 11:37:49

【Dify内存管理实战】:应对加密PDF高负载解析的7种降耗策略

第一章&#xff1a;加密 PDF 解析的 Dify 内存占用在处理加密 PDF 文件时&#xff0c;Dify 平台因需执行解密、内容提取与语义分析等多阶段操作&#xff0c;容易引发显著的内存占用问题。尤其当批量解析高页数或强加密的 PDF 文档时&#xff0c;Java 虚拟机&#xff08;JVM&…

作者头像 李华
网站建设 2026/8/10 5:25:28

Docker网络配置踩坑实录,90%工程师都忽略的Agent通信细节

第一章&#xff1a;Docker网络配置踩坑实录&#xff0c;90%工程师都忽略的Agent通信细节在微服务架构中&#xff0c;Docker容器间的网络通信是系统稳定运行的关键。然而&#xff0c;许多工程师在部署监控Agent或日志采集器时&#xff0c;常因网络模式配置不当导致数据无法上报。…

作者头像 李华