@ohos-ports/tarojs-cli 0.0.0-stage → 4.3.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (223) hide show
  1. package/LICENSE +174 -0
  2. package/README.md +0 -3
  3. package/bin/taro +7 -0
  4. package/dist/cli.d.ts +6 -0
  5. package/dist/cli.js +252 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/commands/customCommand.d.ts +5 -0
  8. package/dist/commands/customCommand.js +23 -0
  9. package/dist/commands/customCommand.js.map +1 -0
  10. package/dist/config/index.d.ts +8 -0
  11. package/dist/config/index.js +10 -0
  12. package/dist/config/index.js.map +1 -0
  13. package/dist/config/packagesManagement.d.ts +19 -0
  14. package/dist/config/packagesManagement.js +22 -0
  15. package/dist/config/packagesManagement.js.map +1 -0
  16. package/dist/create/constants.d.ts +1 -0
  17. package/dist/create/constants.js +5 -0
  18. package/dist/create/constants.js.map +1 -0
  19. package/dist/create/creator.d.ts +9 -0
  20. package/dist/create/creator.js +31 -0
  21. package/dist/create/creator.js.map +1 -0
  22. package/dist/create/fetchTemplate.d.ts +8 -0
  23. package/dist/create/fetchTemplate.js +137 -0
  24. package/dist/create/fetchTemplate.js.map +1 -0
  25. package/dist/create/page.d.ts +65 -0
  26. package/dist/create/page.js +252 -0
  27. package/dist/create/page.js.map +1 -0
  28. package/dist/create/plugin.d.ts +16 -0
  29. package/dist/create/plugin.js +48 -0
  30. package/dist/create/plugin.js.map +1 -0
  31. package/dist/create/project.d.ts +80 -0
  32. package/dist/create/project.js +519 -0
  33. package/dist/create/project.js.map +1 -0
  34. package/dist/doctor/index.d.ts +4 -0
  35. package/dist/doctor/index.js +32 -0
  36. package/dist/doctor/index.js.map +1 -0
  37. package/dist/index.d.ts +16 -0
  38. package/dist/index.js +21 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/presets/commands/build.d.ts +3 -0
  41. package/dist/presets/commands/build.js +239 -0
  42. package/dist/presets/commands/build.js.map +1 -0
  43. package/dist/presets/commands/config.d.ts +3 -0
  44. package/dist/presets/commands/config.js +88 -0
  45. package/dist/presets/commands/config.js.map +1 -0
  46. package/dist/presets/commands/create.d.ts +3 -0
  47. package/dist/presets/commands/create.js +91 -0
  48. package/dist/presets/commands/create.js.map +1 -0
  49. package/dist/presets/commands/global-config.d.ts +3 -0
  50. package/dist/presets/commands/global-config.js +139 -0
  51. package/dist/presets/commands/global-config.js.map +1 -0
  52. package/dist/presets/commands/help.d.ts +3 -0
  53. package/dist/presets/commands/help.js +29 -0
  54. package/dist/presets/commands/help.js.map +1 -0
  55. package/dist/presets/commands/info.d.ts +3 -0
  56. package/dist/presets/commands/info.js +79 -0
  57. package/dist/presets/commands/info.js.map +1 -0
  58. package/dist/presets/commands/init.d.ts +3 -0
  59. package/dist/presets/commands/init.js +59 -0
  60. package/dist/presets/commands/init.js.map +1 -0
  61. package/dist/presets/commands/inspect.d.ts +3 -0
  62. package/dist/presets/commands/inspect.js +118 -0
  63. package/dist/presets/commands/inspect.js.map +1 -0
  64. package/dist/presets/commands/update.d.ts +3 -0
  65. package/dist/presets/commands/update.js +171 -0
  66. package/dist/presets/commands/update.js.map +1 -0
  67. package/dist/presets/constant/hooks.d.ts +13 -0
  68. package/dist/presets/constant/hooks.js +17 -0
  69. package/dist/presets/constant/hooks.js.map +1 -0
  70. package/dist/presets/constant/index.d.ts +1 -0
  71. package/dist/presets/constant/index.js +18 -0
  72. package/dist/presets/constant/index.js.map +1 -0
  73. package/dist/presets/files/generateFrameworkInfo.d.ts +3 -0
  74. package/dist/presets/files/generateFrameworkInfo.js +30 -0
  75. package/dist/presets/files/generateFrameworkInfo.js.map +1 -0
  76. package/dist/presets/files/generateProjectConfig.d.ts +3 -0
  77. package/dist/presets/files/generateProjectConfig.js +40 -0
  78. package/dist/presets/files/generateProjectConfig.js.map +1 -0
  79. package/dist/presets/files/writeFileToDist.d.ts +3 -0
  80. package/dist/presets/files/writeFileToDist.js +17 -0
  81. package/dist/presets/files/writeFileToDist.js.map +1 -0
  82. package/dist/presets/hooks/build.d.ts +3 -0
  83. package/dist/presets/hooks/build.js +22 -0
  84. package/dist/presets/hooks/build.js.map +1 -0
  85. package/dist/presets/hooks/create.d.ts +3 -0
  86. package/dist/presets/hooks/create.js +11 -0
  87. package/dist/presets/hooks/create.js.map +1 -0
  88. package/dist/presets/index.d.ts +4 -0
  89. package/dist/presets/index.js +17 -0
  90. package/dist/presets/index.js.map +1 -0
  91. package/dist/presets/platforms/plugin.d.ts +3 -0
  92. package/dist/presets/platforms/plugin.js +76 -0
  93. package/dist/presets/platforms/plugin.js.map +1 -0
  94. package/dist/presets/platforms/rn.d.ts +3 -0
  95. package/dist/presets/platforms/rn.js +101 -0
  96. package/dist/presets/platforms/rn.js.map +1 -0
  97. package/dist/util/appConfig.d.ts +11 -0
  98. package/dist/util/appConfig.js +25 -0
  99. package/dist/util/appConfig.js.map +1 -0
  100. package/dist/util/createPage.d.ts +9 -0
  101. package/dist/util/createPage.js +117 -0
  102. package/dist/util/createPage.js.map +1 -0
  103. package/dist/util/defineConfig.d.ts +17 -0
  104. package/dist/util/defineConfig.js +12 -0
  105. package/dist/util/defineConfig.js.map +1 -0
  106. package/dist/util/index.d.ts +23 -0
  107. package/dist/util/index.js +125 -0
  108. package/dist/util/index.js.map +1 -0
  109. package/dist/util/types.d.ts +58 -0
  110. package/dist/util/types.js +3 -0
  111. package/dist/util/types.js.map +1 -0
  112. package/global.d.ts +4 -0
  113. package/index.js +3 -0
  114. package/package.json +76 -4
  115. package/postinstall.js +14 -0
  116. package/src/__tests__/__mocks__/presets.ts +15 -0
  117. package/src/__tests__/build-config.spec.ts +99 -0
  118. package/src/__tests__/cli.spec.ts +233 -0
  119. package/src/__tests__/config.spec.ts +232 -0
  120. package/src/__tests__/doctor-config.spec.ts +805 -0
  121. package/src/__tests__/doctor-eslint.spec.ts +31 -0
  122. package/src/__tests__/doctor-recommand.spec.ts +158 -0
  123. package/src/__tests__/doctor.spec.ts +77 -0
  124. package/src/__tests__/dotenv-parse.spec.ts +105 -0
  125. package/src/__tests__/env/.env +2 -0
  126. package/src/__tests__/fixtures/default/.env +3 -0
  127. package/src/__tests__/fixtures/default/.env.development +1 -0
  128. package/src/__tests__/fixtures/default/.env.local +1 -0
  129. package/src/__tests__/fixtures/default/.env.pre +3 -0
  130. package/src/__tests__/fixtures/default/.env.production +1 -0
  131. package/src/__tests__/fixtures/default/.env.uat +5 -0
  132. package/src/__tests__/fixtures/default/.env.uat.local +1 -0
  133. package/src/__tests__/fixtures/default/babel.config.js +10 -0
  134. package/src/__tests__/fixtures/default/config/dev.js +9 -0
  135. package/src/__tests__/fixtures/default/config/index.js +84 -0
  136. package/src/__tests__/fixtures/default/config/prod.js +18 -0
  137. package/src/__tests__/fixtures/default/package.json +38 -0
  138. package/src/__tests__/fixtures/default/src/app.config.js +11 -0
  139. package/src/__tests__/fixtures/default/src/app.js +16 -0
  140. package/src/__tests__/fixtures/default/src/app.scss +0 -0
  141. package/src/__tests__/fixtures/default/src/index.html +19 -0
  142. package/src/__tests__/fixtures/default/src/pages/index/index.config.js +3 -0
  143. package/src/__tests__/fixtures/default/src/pages/index/index.jsx +22 -0
  144. package/src/__tests__/fixtures/default/src/pages/index/index.scss +0 -0
  145. package/src/__tests__/info.spec.ts +74 -0
  146. package/src/__tests__/inspect.spec.ts +163 -0
  147. package/src/__tests__/project.spec.ts +304 -0
  148. package/src/__tests__/update.spec.ts +324 -0
  149. package/src/__tests__/utils/index.ts +54 -0
  150. package/src/cli.ts +250 -0
  151. package/src/commands/customCommand.ts +26 -0
  152. package/src/config/index.ts +7 -0
  153. package/src/config/manifest.default.json +35 -0
  154. package/src/config/packagesManagement.ts +20 -0
  155. package/src/config/rn-stylelint.json +5 -0
  156. package/src/config/tsconfig.json +24 -0
  157. package/src/create/constants.ts +1 -0
  158. package/src/create/creator.ts +37 -0
  159. package/src/create/fetchTemplate.ts +152 -0
  160. package/src/create/page.ts +299 -0
  161. package/src/create/plugin.ts +55 -0
  162. package/src/create/project.ts +591 -0
  163. package/src/doctor/index.ts +27 -0
  164. package/src/index.ts +24 -0
  165. package/src/presets/commands/build.ts +227 -0
  166. package/src/presets/commands/config.ts +86 -0
  167. package/src/presets/commands/create.ts +105 -0
  168. package/src/presets/commands/global-config.ts +140 -0
  169. package/src/presets/commands/help.ts +19 -0
  170. package/src/presets/commands/info.ts +77 -0
  171. package/src/presets/commands/init.ts +66 -0
  172. package/src/presets/commands/inspect.ts +138 -0
  173. package/src/presets/commands/update.ts +179 -0
  174. package/src/presets/constant/hooks.ts +14 -0
  175. package/src/presets/constant/index.ts +1 -0
  176. package/src/presets/files/generateFrameworkInfo.ts +30 -0
  177. package/src/presets/files/generateProjectConfig.ts +41 -0
  178. package/src/presets/files/writeFileToDist.ts +17 -0
  179. package/src/presets/hooks/build.ts +22 -0
  180. package/src/presets/hooks/create.ts +11 -0
  181. package/src/presets/index.ts +15 -0
  182. package/src/presets/platforms/plugin.ts +81 -0
  183. package/src/presets/platforms/rn.ts +113 -0
  184. package/src/util/appConfig.ts +29 -0
  185. package/src/util/createPage.ts +132 -0
  186. package/src/util/defineConfig.ts +22 -0
  187. package/src/util/index.ts +127 -0
  188. package/src/util/types.ts +81 -0
  189. package/templates/default/.husky/commit-msg +4 -0
  190. package/templates/default/_editorconfig +12 -0
  191. package/templates/default/_env.development +2 -0
  192. package/templates/default/_env.production +1 -0
  193. package/templates/default/_env.test +1 -0
  194. package/templates/default/_eslintrc +11 -0
  195. package/templates/default/_gitignore +8 -0
  196. package/templates/default/babel.config.js +14 -0
  197. package/templates/default/commitlint.config.mjs +1 -0
  198. package/templates/default/config/dev.js +10 -0
  199. package/templates/default/config/index.js +106 -0
  200. package/templates/default/config/prod.js +46 -0
  201. package/templates/default/package.json.tmpl +158 -0
  202. package/templates/default/project.config.json +15 -0
  203. package/templates/default/src/app.config.js +11 -0
  204. package/templates/default/src/app.css +0 -0
  205. package/templates/default/src/app.js +44 -0
  206. package/templates/default/src/index.html +17 -0
  207. package/templates/default/src/pages/index/index.config.js +3 -0
  208. package/templates/default/src/pages/index/index.css +0 -0
  209. package/templates/default/src/pages/index/index.jsx +15 -0
  210. package/templates/default/src/pages/index/index.vue +23 -0
  211. package/templates/default/stylelint.config.mjs +4 -0
  212. package/templates/default/template_creator.js +77 -0
  213. package/templates/default/tsconfig.json +32 -0
  214. package/templates/default/types/global.d.ts +35 -0
  215. package/templates/default/types/solid.d.ts +12 -0
  216. package/templates/default/types/vue.d.ts +10 -0
  217. package/templates/global-config/index.json +4 -0
  218. package/templates/global-config/package.json +5 -0
  219. package/templates/plugin-compile/README.md +32 -0
  220. package/templates/plugin-compile/index.js +3 -0
  221. package/templates/plugin-compile/package.json.tmpl +43 -0
  222. package/templates/plugin-compile/src/index.ts +153 -0
  223. package/templates/plugin-compile/tsconfig.json +29 -0
@@ -0,0 +1,20 @@
1
+ const packagesManagement = {
2
+ yarn: {
3
+ command: 'yarn install',
4
+ globalCommand: 'yarn global add @tarojs/cli'
5
+ },
6
+ pnpm: {
7
+ command: 'pnpm install',
8
+ globalCommand: 'pnpm add -g @tarojs/cli'
9
+ },
10
+ cnpm: {
11
+ command: 'cnpm install',
12
+ globalCommand: 'cnpm i -g @tarojs/cli'
13
+ },
14
+ npm: {
15
+ command: 'npm install',
16
+ globalCommand: 'npm i -g @tarojs/cli'
17
+ }
18
+ }
19
+
20
+ export default packagesManagement
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "stylelint-config-taro-rn",
3
+ "rules": {
4
+ }
5
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowSyntheticDefaultImports": true,
4
+ "baseUrl": ".",
5
+ "declaration": false,
6
+ "experimentalDecorators": true,
7
+ "jsx": "react",
8
+ "jsxFactory": "React.createElement",
9
+ "module": "commonjs",
10
+ "moduleResolution": "node",
11
+ "noImplicitAny": false,
12
+ "noUnusedLocals": true,
13
+ "outDir": "./dist/",
14
+ "preserveConstEnums": true,
15
+ "removeComments": false,
16
+ "rootDir": ".",
17
+ "sourceMap": true,
18
+ "strictNullChecks": true,
19
+ "target": "es6"
20
+ },
21
+ "include": ["src/**/*"],
22
+ "exclude": ["node_modules"],
23
+ "compileOnSave": false
24
+ }
@@ -0,0 +1 @@
1
+ export const TEMPLATE_CREATOR = 'template_creator.js'
@@ -0,0 +1,37 @@
1
+ import * as path from 'node:path'
2
+
3
+ import { fs } from '@tarojs/helper'
4
+
5
+ import { getRootPath } from '../util'
6
+
7
+ export default class Creator {
8
+ protected _rootPath: string
9
+ public rootPath: string
10
+
11
+ constructor (sourceRoot?: string) {
12
+ this.rootPath = this.sourceRoot(sourceRoot || path.join(getRootPath()))
13
+ this.init()
14
+ }
15
+
16
+ init () {}
17
+
18
+ sourceRoot (rootPath?: string) {
19
+ if (typeof rootPath === 'string') {
20
+ this._rootPath = path.resolve(rootPath)
21
+ }
22
+ if (!fs.existsSync(this._rootPath)) {
23
+ fs.ensureDirSync(this._rootPath)
24
+ }
25
+ return this._rootPath
26
+ }
27
+
28
+ templatePath (...args: string[]): string {
29
+ let filepath = path.join.apply(path, args)
30
+ if (!path.isAbsolute(filepath)) {
31
+ filepath = path.join(this._rootPath, 'templates', filepath)
32
+ }
33
+ return filepath
34
+ }
35
+
36
+ write () {}
37
+ }
@@ -0,0 +1,152 @@
1
+ import * as path from 'node:path'
2
+
3
+ import { chalk, fs } from '@tarojs/helper'
4
+ import * as AdmZip from 'adm-zip'
5
+ import axios from 'axios'
6
+ import * as download from 'download-git-repo'
7
+ import * as ora from 'ora'
8
+
9
+ import { getTemplateSourceType, readDirWithFileTypes } from '../util'
10
+ import { TEMPLATE_CREATOR } from './constants'
11
+
12
+ export interface ITemplates {
13
+ name: string
14
+ value: string
15
+ platforms?: string | string[]
16
+ desc?: string
17
+ compiler?: string[]
18
+ }
19
+
20
+ const TEMP_DOWNLOAD_FOLDER = 'taro-temp'
21
+
22
+ export default function fetchTemplate (templateSource: string, templateRootPath: string, clone?: boolean): Promise<ITemplates[]> {
23
+ const type = getTemplateSourceType(templateSource)
24
+ const tempPath = path.join(templateRootPath, TEMP_DOWNLOAD_FOLDER)
25
+ let name: string
26
+ // eslint-disable-next-line no-async-promise-executor
27
+ return new Promise<void>(async (resolve) => {
28
+ // 下载文件的缓存目录
29
+ if (fs.existsSync(tempPath)) await fs.remove(tempPath)
30
+ await fs.mkdirp(templateRootPath)
31
+ await fs.mkdir(tempPath)
32
+
33
+ const spinner = ora(`正在从 ${templateSource} 拉取远程模板...`).start()
34
+
35
+ if (type === 'git') {
36
+ name = path.basename(templateSource)
37
+ download(templateSource, path.join(tempPath, name), { clone }, async error => {
38
+ if (error) {
39
+ console.log(error)
40
+ spinner.color = 'red'
41
+ spinner.fail(chalk.red('拉取远程模板仓库失败!'))
42
+ await fs.remove(tempPath)
43
+ return resolve()
44
+ }
45
+ spinner.color = 'green'
46
+ spinner.succeed(`${chalk.grey('拉取远程模板仓库成功!')}`)
47
+ resolve()
48
+ })
49
+ } else if (type === 'url') {
50
+ // url 模板源,因为不知道来源名称,临时取名方便后续开发者从列表中选择
51
+ name = 'from-remote-url'
52
+ const zipPath = path.join(tempPath, name + '.zip')
53
+ const unZipPath = path.join(tempPath, name)
54
+ axios.get<fs.ReadStream>(templateSource, { responseType: 'stream' })
55
+ .then(response => {
56
+ const ws = fs.createWriteStream(zipPath)
57
+ response.data.pipe(ws)
58
+ ws.on('finish', () => {
59
+ // unzip
60
+ const zip = new AdmZip(zipPath)
61
+ zip.extractAllTo(unZipPath, true)
62
+ const files = readDirWithFileTypes(unZipPath).filter(
63
+ file => !file.name.startsWith('.') && file.isDirectory && file.name !== '__MACOSX'
64
+ )
65
+
66
+ if (files.length !== 1) {
67
+ spinner.color = 'red'
68
+ spinner.fail(chalk.red(`拉取远程模板仓库失败!\n${new Error('远程模板源组织格式错误')}`))
69
+ return resolve()
70
+ }
71
+ name = path.join(name, files[0].name)
72
+
73
+ spinner.color = 'green'
74
+ spinner.succeed(`${chalk.grey('拉取远程模板仓库成功!')}`)
75
+ resolve()
76
+ })
77
+ ws.on('error', error => { throw error })
78
+ })
79
+ .catch(async error => {
80
+ spinner.color = 'red'
81
+ spinner.fail(chalk.red(`拉取远程模板仓库失败!\n${error}`))
82
+ await fs.remove(tempPath)
83
+ return resolve()
84
+ })
85
+ }
86
+ }).then(async () => {
87
+ const templateFolder = name ? path.join(tempPath, name) : ''
88
+
89
+ // 下载失败,只显示默认模板
90
+ if (!fs.existsSync(templateFolder)) return Promise.resolve([])
91
+
92
+ const isTemplateGroup = !(
93
+ fs.existsSync(path.join(templateFolder, 'package.json')) ||
94
+ fs.existsSync(path.join(templateFolder, 'package.json.tmpl'))
95
+ )
96
+
97
+ if (isTemplateGroup) {
98
+ // 模板组
99
+ const files = readDirWithFileTypes(templateFolder)
100
+ .filter(file => !file.name.startsWith('.') && file.isDirectory && file.name !== '__MACOSX')
101
+ .map(file => file.name)
102
+ await Promise.all(
103
+ files.map(file => {
104
+ const src = path.join(templateFolder, file)
105
+ const dest = path.join(templateRootPath, file)
106
+ return fs.move(src, dest, { overwrite: true })
107
+ })
108
+ )
109
+ await fs.remove(tempPath)
110
+
111
+ const res: ITemplates[] = files.map(name => {
112
+ const creatorFile = path.join(templateRootPath, name, TEMPLATE_CREATOR)
113
+
114
+ if (!fs.existsSync(creatorFile)) return { name, value: name }
115
+ const { name: displayName, platforms = '', desc = '', isPrivate = false, compiler } = require(creatorFile)
116
+ if (isPrivate) return null
117
+
118
+ return {
119
+ name: displayName || name,
120
+ value: name,
121
+ platforms,
122
+ compiler,
123
+ desc
124
+ }
125
+ }).filter(Boolean) as ITemplates[]
126
+
127
+ return Promise.resolve(res)
128
+ } else {
129
+ // 单模板
130
+ await fs.move(templateFolder, path.join(templateRootPath, name), { overwrite: true })
131
+ await fs.remove(tempPath)
132
+
133
+ let res: ITemplates = { name, value: name, desc: type === 'url' ? templateSource : '' }
134
+
135
+ const creatorFile = path.join(templateRootPath, name, TEMPLATE_CREATOR)
136
+
137
+ if (fs.existsSync(creatorFile)) {
138
+ const { name: displayName, platforms = '', desc = '', compiler } = require(creatorFile)
139
+
140
+ res = {
141
+ name: displayName || name,
142
+ value: name,
143
+ platforms,
144
+ compiler,
145
+ desc: desc || templateSource
146
+ }
147
+ }
148
+
149
+ return Promise.resolve([res])
150
+ }
151
+ })
152
+ }
@@ -0,0 +1,299 @@
1
+ import * as path from 'node:path'
2
+
3
+ import { CompilerType, createPage as createPageBinding, CSSType, FrameworkType, NpmType, PeriodType } from '@tarojs/binding'
4
+ import { babelKit, chalk, DEFAULT_TEMPLATE_SRC, fs, getUserHomeDir, resolveScriptPath, TARO_BASE_CONFIG, TARO_CONFIG_FOLDER } from '@tarojs/helper'
5
+
6
+ import { getPkgVersion, getRootPath, isNil } from '../util'
7
+ import { modifyPagesOrSubPackages } from '../util/createPage'
8
+ import { TEMPLATE_CREATOR } from './constants'
9
+ import Creator from './creator'
10
+ import fetchTemplate from './fetchTemplate'
11
+
12
+ export interface IPageConf {
13
+ projectDir: string
14
+ projectName: string
15
+ npm: NpmType
16
+ template: string
17
+ clone?: boolean
18
+ templateSource?: string
19
+ description?: string
20
+ pageName: string
21
+ date?: string
22
+ framework: FrameworkType
23
+ css: CSSType
24
+ typescript?: boolean
25
+ compiler?: CompilerType
26
+ isCustomTemplate?: boolean
27
+ customTemplatePath?: string
28
+ pageDir?: string
29
+ subPkg?: string
30
+ }
31
+ interface IPageArgs extends IPageConf {
32
+ modifyCustomTemplateConfig : TGetCustomTemplate
33
+ afterCreate?: TAfterCreate
34
+ }
35
+ interface ITemplateInfo {
36
+ css: CSSType
37
+ typescript?: boolean
38
+ compiler?: CompilerType
39
+ template?: string
40
+ templateSource?: string
41
+ clone?: boolean
42
+ }
43
+
44
+ type TCustomTemplateInfo = Omit<ITemplateInfo & {
45
+ isCustomTemplate?: boolean
46
+ customTemplatePath?: string
47
+ }, 'template'>
48
+
49
+ export type TSetCustomTemplateConfig = (customTemplateConfig: TCustomTemplateInfo) => void
50
+
51
+ type TGetCustomTemplate = (cb: TSetCustomTemplateConfig) => Promise<void>
52
+ type TAfterCreate = (state: boolean) => void
53
+
54
+ const DEFAULT_TEMPLATE_INFO = {
55
+ name: 'default',
56
+ css: CSSType.None,
57
+ typescript: false,
58
+ compiler: CompilerType.Webpack5,
59
+ framework: FrameworkType.React
60
+ }
61
+
62
+ export enum ConfigModificationState {
63
+ Success,
64
+ Fail,
65
+ NeedLess
66
+ }
67
+
68
+ export type ModifyCallback = (state: ConfigModificationState) => void
69
+
70
+ export default class Page extends Creator {
71
+ public rootPath: string
72
+ public conf: IPageConf
73
+ private modifyCustomTemplateConfig: TGetCustomTemplate
74
+ private afterCreate: TAfterCreate | undefined
75
+ private pageEntryPath: string
76
+
77
+ constructor (args: IPageArgs) {
78
+ super()
79
+ this.rootPath = this._rootPath
80
+ const { modifyCustomTemplateConfig, afterCreate, ...otherOptions } = args
81
+ this.conf = Object.assign(
82
+ {
83
+ projectDir: '',
84
+ projectName: '',
85
+ template: '',
86
+ description: '',
87
+ pageDir: ''
88
+ },
89
+ otherOptions
90
+ )
91
+
92
+ this.conf.projectName = path.basename(this.conf.projectDir)
93
+ this.modifyCustomTemplateConfig = modifyCustomTemplateConfig
94
+ this.afterCreate = afterCreate
95
+ this.processPageName()
96
+ }
97
+
98
+ processPageName () {
99
+ const { pageName } = this.conf
100
+ // todo 目前还没有对 subPkg 和 pageName 这两个字段做 格式验证或者处理
101
+ const lastDirSplitSymbolIndex = pageName.lastIndexOf('/')
102
+ if (lastDirSplitSymbolIndex !== -1) {
103
+ this.conf.pageDir = pageName.substring(0, lastDirSplitSymbolIndex)
104
+ this.conf.pageName = pageName.substring(lastDirSplitSymbolIndex + 1)
105
+ }
106
+ }
107
+
108
+ getPkgPath () {
109
+ const projectDir = this.conf.projectDir as string
110
+ let pkgPath = path.join(projectDir, 'package.json')
111
+ if (!fs.existsSync(pkgPath)) {
112
+ // 适配 云开发 项目
113
+ pkgPath = path.join(projectDir, 'client', 'package.json')
114
+ if (!fs.existsSync(pkgPath)) {
115
+ console.log(chalk.yellow('请在项目根目录下执行 taro create 命令!'))
116
+ process.exit(0)
117
+ }
118
+ }
119
+ return pkgPath
120
+ }
121
+
122
+ getPkgTemplateInfo () {
123
+ const pkg = fs.readJSONSync(this.getPkgPath())
124
+ const templateInfo = pkg.templateInfo || DEFAULT_TEMPLATE_INFO
125
+ // set template name
126
+ templateInfo.template = templateInfo.name
127
+ delete templateInfo.name
128
+ return templateInfo
129
+ }
130
+
131
+ setPageEntryPath (files: string[], handler) {
132
+ const configFileName = files.find((filename) => /\.config\.(js|ts)$/.test(filename))
133
+ if (!configFileName) return
134
+ const getPageFn = handler[configFileName]
135
+ const { setPageName = '', setSubPkgName = '' } = getPageFn?.(() => {}, this.conf) || {}
136
+ if (this.conf.subPkg) {
137
+ this.pageEntryPath = setSubPkgName.replace(/\.config\.(js|ts)$/, '')
138
+ } else {
139
+ this.pageEntryPath = setPageName.replace(/\.config\.(js|ts)$/, '')
140
+ }
141
+ }
142
+
143
+ setCustomTemplateConfig (customTemplateConfig: TCustomTemplateInfo) {
144
+ const pkgTemplateInfo = this.getPkgTemplateInfo()
145
+ const { compiler, css, customTemplatePath, typescript } = customTemplateConfig
146
+ const conf = {
147
+ compiler: compiler || pkgTemplateInfo.compiler,
148
+ css: css || pkgTemplateInfo.css,
149
+ typescript: !isNil(typescript) ? typescript : pkgTemplateInfo.typescript,
150
+ customTemplatePath,
151
+ isCustomTemplate: true,
152
+ }
153
+ this.setTemplateConfig(conf)
154
+ }
155
+
156
+ setTemplateConfig (templateInfo: ITemplateInfo) {
157
+ this.conf = Object.assign(this.conf, templateInfo)
158
+ }
159
+
160
+ async fetchTemplates () {
161
+ const homedir = getUserHomeDir()
162
+ let templateSource = DEFAULT_TEMPLATE_SRC
163
+ if (!homedir) chalk.yellow('找不到用户根目录,使用默认模版源!')
164
+
165
+ if (this.conf.templateSource) {
166
+ templateSource = this.conf.templateSource
167
+ } else {
168
+ const taroConfigPath = path.join(homedir, TARO_CONFIG_FOLDER)
169
+ const taroConfig = path.join(taroConfigPath, TARO_BASE_CONFIG)
170
+ if (fs.existsSync(taroConfig)) {
171
+ const config = await fs.readJSON(taroConfig)
172
+ templateSource = config && config.templateSource ? config.templateSource : DEFAULT_TEMPLATE_SRC
173
+ } else {
174
+ await fs.createFile(taroConfig)
175
+ await fs.writeJSON(taroConfig, { templateSource })
176
+ templateSource = DEFAULT_TEMPLATE_SRC
177
+ }
178
+ }
179
+
180
+ // 从模板源下载模板
181
+ await fetchTemplate(templateSource, this.templatePath(''), this.conf.clone)
182
+ }
183
+
184
+ async create () {
185
+ const date = new Date()
186
+ this.conf.date = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
187
+ // apply 插件,由插件设置自定义模版 config
188
+ await this.modifyCustomTemplateConfig(this.setCustomTemplateConfig.bind(this))
189
+ if (!this.conf.isCustomTemplate) {
190
+ const pkgTemplateInfo = this.getPkgTemplateInfo()
191
+ this.setTemplateConfig(pkgTemplateInfo)
192
+ if (!fs.existsSync(this.templatePath(this.conf.template))) {
193
+ await this.fetchTemplates()
194
+ }
195
+ }
196
+ this.write()
197
+ }
198
+
199
+ updateAppConfig () {
200
+ const { parse, generate, traverse } = babelKit
201
+
202
+ let modifyState: ConfigModificationState = ConfigModificationState.Fail
203
+ const { subPkg, projectDir, typescript } = this.conf
204
+ const [sourceString, pageString] = this.pageEntryPath.split('/src/')
205
+ const appConfigPath = resolveScriptPath(path.join(projectDir, sourceString, 'src', 'app.config'))
206
+ if (!fs.existsSync(appConfigPath)) {
207
+ return console.log(
208
+ `${chalk.red('x ')}${chalk.grey(`无法获取 ${appConfigPath} 配置文件,请手动到配置文件中补全新页面信息`)}`
209
+ )
210
+ }
211
+ const configFileContent = fs.readFileSync(appConfigPath, 'utf-8')
212
+ const ast = parse(configFileContent, {
213
+ sourceType: 'module',
214
+ plugins: typescript ? ['typescript'] : []
215
+ })
216
+
217
+ const callback = (state: ConfigModificationState) => {
218
+ modifyState = state
219
+ }
220
+
221
+ traverse(ast as any, {
222
+ ExportDefaultDeclaration (path) {
223
+ modifyPagesOrSubPackages({
224
+ path,
225
+ fullPagePath: pageString,
226
+ subPkgRootPath: subPkg,
227
+ callback
228
+ })
229
+ },
230
+ })
231
+
232
+ switch (modifyState as ConfigModificationState) {
233
+ case ConfigModificationState.Fail:
234
+ console.log(`${chalk.red('x ')}${chalk.grey(`自动补全新页面信息失败, 请手动到 ${appConfigPath} 文件中补全新页面信息`)}`)
235
+ break
236
+ case ConfigModificationState.Success:
237
+ {
238
+ const newCode = generate(ast as any, { retainLines: true })
239
+ fs.writeFileSync(appConfigPath, newCode.code)
240
+ console.log(`${chalk.green('✔ ')}${chalk.grey(`新页面信息已在 ${appConfigPath} 文件中自动补全`)}`)
241
+ break
242
+ }
243
+ case ConfigModificationState.NeedLess:
244
+ console.log(`${chalk.green('✔ ')}${chalk.grey(`新页面信息已存在在 ${appConfigPath} 文件中,不需要补全`)}`)
245
+ break
246
+ }
247
+ }
248
+
249
+ write () {
250
+ const { projectName, projectDir, template, pageName, isCustomTemplate, customTemplatePath, subPkg, pageDir } = this.conf as IPageConf
251
+ let templatePath
252
+
253
+ if (isCustomTemplate) {
254
+ templatePath = customTemplatePath
255
+ } else {
256
+ templatePath = this.templatePath(template)
257
+ }
258
+
259
+ if (!fs.existsSync(templatePath)) return console.log(chalk.red(`创建页面错误:找不到模板${templatePath}`))
260
+
261
+ // 引入模板编写者的自定义逻辑
262
+ const handlerPath = path.join(templatePath, TEMPLATE_CREATOR)
263
+ const basePageFiles = fs.existsSync(handlerPath) ? require(handlerPath).basePageFiles : []
264
+ const files = Array.isArray(basePageFiles) ? basePageFiles : []
265
+ const handler = fs.existsSync(handlerPath) ? require(handlerPath).handler : {}
266
+
267
+ this.setPageEntryPath(files, handler)
268
+
269
+ createPageBinding({
270
+ pageDir,
271
+ subPkg,
272
+ projectDir,
273
+ projectName,
274
+ template,
275
+ framework: this.conf.framework,
276
+ css: this.conf.css || CSSType.None,
277
+ typescript: this.conf.typescript,
278
+ compiler: this.conf.compiler,
279
+ templateRoot: getRootPath(),
280
+ version: getPkgVersion(),
281
+ date: this.conf.date,
282
+ description: this.conf.description,
283
+ pageName,
284
+ isCustomTemplate,
285
+ customTemplatePath,
286
+ basePageFiles: files,
287
+ period: PeriodType.CreatePage,
288
+ }, handler).then(() => {
289
+ console.log(`${chalk.green('✔ ')}${chalk.grey(`创建页面 ${this.conf.pageName} 成功!`)}`)
290
+ this.updateAppConfig()
291
+ this.afterCreate && this.afterCreate(true)
292
+ }).catch(err => {
293
+ console.log(err)
294
+ this.afterCreate && this.afterCreate(false)
295
+ })
296
+ }
297
+ }
298
+
299
+ export type { Page as PageCreator }
@@ -0,0 +1,55 @@
1
+ import * as path from 'node:path'
2
+
3
+ import { createPlugin } from '@tarojs/binding'
4
+ import { chalk, fs } from '@tarojs/helper'
5
+
6
+ import { getRootPath } from '../util'
7
+ import Creator from './creator'
8
+
9
+ export interface IPluginConf {
10
+ pluginName: string
11
+ type: string
12
+ description?: string
13
+ projectDir: string
14
+ projectName: string
15
+ template: string
16
+ version:string
17
+ }
18
+
19
+ export default class Plugin extends Creator {
20
+ public conf: IPluginConf
21
+
22
+ constructor (options: IPluginConf) {
23
+ super()
24
+ this.conf = {
25
+ ...options,
26
+ projectName: path.basename(options.projectDir),
27
+ version: this.getCliVersion()
28
+ }
29
+ }
30
+
31
+ getCliVersion () {
32
+ const pkgPath = path.join(this._rootPath, 'package.json')
33
+ const pkg = fs.readJSONSync(pkgPath)
34
+ return pkg.version
35
+ }
36
+
37
+ async create () {
38
+ const { projectDir, template, pluginName } = this.conf
39
+ const templatePath = this.templatePath(template)
40
+
41
+ if (!fs.existsSync(templatePath)) {
42
+ console.log(chalk.red(`创建插件失败:找不到模板${templatePath}`))
43
+ return
44
+ }
45
+ createPlugin({
46
+ projectRoot: projectDir,
47
+ projectName: pluginName,
48
+ templateRoot: getRootPath(),
49
+ template,
50
+ version: this.conf.version,
51
+ description: this.conf.description,
52
+ pluginType: this.conf.type,
53
+ })
54
+ }
55
+ }