当前位置: 首页 > news >正文

现代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
http://www.cnnetsun.cn/news/90198.html

相关文章:

  • Traefik:为云原生而生的自动化反向代理
  • P1043 [NOIP 2003 普及组] 数字游戏
  • Web安全攻防学习图谱:90天从网安小白到漏洞猎人(超详细),看这一篇就够了!
  • 【Docker镜像优化黄金法则】:让边缘Agent更小更快更安全
  • 前端vue3 web端中实现拖拽功能实现列表排序
  • 【音视频开发必看】Dify 1.7.0音频转换避坑指南:5大常见错误及修复方案
  • VSCode+PlatfoemIO+ESP32-Cam + MB烧录器 入门测试
  • 【加密PDF解析避坑指南】:Dify错误处理的5大核心策略与实战技巧
  • 性能测试入门:使用 Playwright 测量关键 Web 性能指标
  • 从入门到精通:R语言极值分布拟合在气象数据中的4个关键步骤
  • 仅1%人掌握的建模技术:R语言金融相关性矩阵稀疏化处理实战
  • 超越传统PLM理念,定义行业新标准:全星研发项目管理APQP软件系统
  • 【安全专家亲授】私有化Dify的SSL配置秘诀:保障数据传输不被窃取
  • Vue3+JS 高级前端面试题
  • 海康威视智能工厂,是如何走向“领航”的?
  • 《深入昇腾底层:Ascend C 编程模型与高性能算子开发实战》
  • 实战 Ascend C:从零实现高性能自定义算子
  • 掌握这3种R包,轻松完成空间转录组细胞轨迹建模!
  • 【Dify Tesseract字体适配终极指南】:破解OCR识别失败的9大字体陷阱
  • Docker + 智能Agent日志管理新思路(仅限高级工程师掌握的3种架构模式)
  • 揭秘空间转录组细胞类型注释:如何用R语言精准识别每一种细胞
  • [吾爱大神原创工具] 电话号码过滤,号码排序-乱序,清除非手机号,消重,导出(依旧颜值高)
  • Dify平台Agent版本管理全解析:从入门到高可用架构设计
  • 为什么90%的生物信息分析师都在用R做RNA结构研究?真相令人震惊
  • 【稀缺资源】Dify + Tesseract 5.3多语言支持实现路径首次公开
  • 还在手动写Dify用例?Agent驱动自动化测试已成主流!
  • RSA 加密体制及其安全性分析
  • 【视频帧提取效率翻倍秘籍】:Dify帧率设置背后的黄金参数揭秘
  • 在C#上运行YOLOv11模型---CPU版
  • 关于uniapp vue2 canvas重绘元素节点时,提示cos of null相关异常警告,导致js线程崩溃,vue响应式丢失的问题