Taro使用模块化开发,以提升开发效率
duxapp是基于Taro二次开发的模块化框架
使用这个框架,结合框架提供的UI库和工具库,能帮助你快速且高质量的完成项目,且能实现同时开发小程序、H5、APP(React Native),并且保证各个端的一致性
duxapp还针对APP开发(React Native)做了大量优化,大大降低了APP发开的难度,你可以阅读React Native教程,了解详情
下面让我来详细介绍如何使用duxapp
何为模块化
什么是模块化?就像npm包一样,我们可以将一些通用的功能或页面编写在一个模块内,提供给多个项目来使用,以提高代码的复用性。
模块的概念 在很多后端框架中很常见,它们可以在应用商店通过安装应用的方式来获得新功能,在前端框架中确很少见到类似的设计方案,当然你其实也可以理解为发布到npm就是一种模块化的设计,但是在Taro中很多功能他并不能发布到npm中,例如页面。页面需要放在项目中,当发布到npm之后就会无法使用
在duxapp框架中的模块化设计原理,和npm的依赖关系是类似的,每个模块有一个配置文件app.json
,里面的依赖字段dependencies
,用来填写我要用到的依赖,就像下面ui库示例
这个模块的配置
{
"name": "duxuiExample",
"description": "ui库示例",
"version": "1.0.13",
"dependencies": [
"duxui",
"duxcms",
"amap",
"echarts",
"wechat"
]
}
和npm依赖不一样的是,这里的依赖不包含版本信息。因为页面等限制条件,你一个项目中,同一个模块无法存在两个不同的版本,因此并未设计指定版本号的功能
依赖关系是逐层查找的,就像npm一样,例如这里依赖的duxui
模块,他的模块配置文件是这样的
{
"name": "duxui",
"description": "DUXUI库",
"version": "1.0.42",
"dependencies": [
"duxapp"
],
"npm": {
"dependencies": {
"b-validate": "^1.5.3",
"react-native-view-shot": "~3.8.0",
"react-native-fast-shadow": "~0.1.1",
"array-tree-filter": "^2.1.0"
}
}
}
在duxui模块中他又使用了duxapp
这个依赖,通过每个模块都去查找,我们最终整理出这样的依赖关系图
那么最终当我们使用下面的命令编译duxuiExample
模块的时候
# 调试小程序
yarn dev:weapp --app=duxuiExample
# 调试h5
yarn dev:h5 --app=duxuiExample
实际被编译的模块就包含下面这些
- duxuiExample
- duxcms
- amap
- echarts
- duxui
- duxappReactNative
- duxapp
使用duxapp
上面介绍了模块化的原理,现在我们来看看,具体要怎么使用这个框架
首先使用cli命令创建一个项目,中途会要求你选择模板,你可以选择 duxui 示例代码(包含所有组件的示例代码 支持RN端)
这个选项,和上面使用的示例一样
npx duxapp-cli create projectName
在使用这个命令之前,确保安装了以下工具和环境
- nodejs 20+
- git命令行工具
- yarn
使用命令npm i yarn -g
安装
安装后会自动安装项目依赖
进入项目目录projectName
,使用上面提到的命令 yarn dev:weapp --app=duxuiExample
或者 yarn dev:h5 --app=duxuiExample
编译为小程序或者H5,使用开发者工具或者浏览器就能预览
可以看到编译命令是在Taro原有的命令基础上增加了 --app=
参数,参数用来指定一个模块,通常你都需要指定这个参数,因为你的项目中除了上面提到的模块之外,大多是时候还会存在其他模块,如果你不指定的话,他会把所有模块都打包进去
通过上面的描述可以看出,其实在一个项目中不是真的只有一个项目,在我的实际开发经验中,我是将很多项目放在一起开发的,我只需要通过 --app=
参数指定我的项目入口文件进行编译,他就是不同的项目
多个项目同时存在,如何保持他们不混乱呢,例如第三方npm依赖,每个项目可能都有不同的npm依赖,这通过下面的章节来介绍
模块
在duxapp框架中,src
目录下每个文件夹将被识别为一个模块,模块一般是像下面这样设计结构的
├── duxapp 模块名称
│ ├── components 模块组件库
│ │ ├── ComponentName 组件
│ │ │ └── index.jsx
│ │ └── index.js 导出需要导出的组件
│ ├── config 配置目录
│ │ ├── route.js 路由配置文件(路径固定)
│ │ ├── theme.js 主题配置文件(路径固定)
│ │ └── themeToScss.js 主题转换函数(路径固定)
│ ├── pages 页面放置文件夹
│ │ └── index 页面文件夹
│ │ ├── index.jsx 页面
│ │ └── index.scss
│ ├── utils 工具库
│ │ ├── index.js 导出工具库
│ │ └── ...you util.js
│ ├── update 模块安装目录
│ │ ├── copy 需要复制到项目的文件(路径固定)
│ │ │ └── ...
│ │ └── index.js 安装脚本 主要针对RN端 插件安装方法(路径固定)
│ ├── app.js 模块入口文件
│ ├── app.json 模块配置文件 包括名称 依赖等(必须)
│ ├── app.scss 全局样式文件(次样式文件无需导入到js文件中,会自动注入全局)
│ ├── changelog.md 更新日志(必须 如果发布)
│ ├── index.js 模块出口文件 可以导出组件和方法给其他模块使用
│ ├── index.html 如果是h5的项目可以自定义index.html,仅当作为入口模块时可用
│ ├── app.config.js 用于覆盖项目全局配置
│ ├── babel.config.js babel配置文件
│ ├── metro.config.js metro配置文件
│ ├── taro.config.js Taro编译配置文件
│ ├── taro.config.prod.js Taro 发布配置文件
│ ├── taro.config.dev.js Taro 调试配置文件
│ └── readme.md 自述文件(必须 如果发布)
关于模块目录的详细内容查看这个 模块结构 获取