UNPKG

3.07 kBPlain TextView Raw
1import * as path from 'path'
2import * as fs from 'fs-extra'
3import { DEFAULT_TEMPLATE_SRC, TARO_CONFIG_FLODER, TARO_BASE_CONFIG, getUserHomeDir, chalk } from '@tarojs/helper'
4
5import Creator from './creator'
6import { createPage } from './init'
7import fetchTemplate from './fetchTemplate'
8
9export interface IPageConf {
10 projectDir: string;
11 projectName: string;
12 template: string;
13 description?: string;
14 pageName: string;
15 css: 'none' | 'sass' | 'stylus' | 'less';
16 typescript?: boolean;
17 date?: string;
18 framework: 'react' | 'nerv' | 'vue' | 'vue3'
19}
20
21export default class Page extends Creator {
22 public rootPath: string
23 public conf: IPageConf
24
25 constructor (options: IPageConf) {
26 super()
27 this.rootPath = this._rootPath
28
29 this.conf = Object.assign(
30 {
31 projectDir: '',
32 projectName: '',
33 template: '',
34 description: ''
35 },
36 options
37 )
38 this.conf.projectName = path.basename(this.conf.projectDir)
39 }
40
41 getPkgPath () {
42 const projectDir = this.conf.projectDir as string
43 let pkgPath = path.join(projectDir, 'package.json')
44 if (!fs.existsSync(pkgPath)) {
45 // 适配 云开发 项目
46 pkgPath = path.join(projectDir, 'client', 'package.json')
47 if (!fs.existsSync(pkgPath)) {
48 console.log(chalk.yellow('请在项目根目录下执行 taro create 命令!'))
49 process.exit(0)
50 }
51 }
52 return pkgPath
53 }
54
55 getTemplateInfo () {
56 const pkg = fs.readJSONSync(this.getPkgPath())
57 const templateInfo = pkg.templateInfo || {
58 name: 'default',
59 css: 'none',
60 typescript: false
61 }
62
63 // set template name
64 templateInfo.template = templateInfo.name
65 delete templateInfo.name
66
67 this.conf = Object.assign(this.conf, templateInfo)
68 }
69
70 async fetchTemplates () {
71 const homedir = getUserHomeDir()
72 let templateSource = DEFAULT_TEMPLATE_SRC
73 if (!homedir) chalk.yellow('找不到用户根目录,使用默认模版源!')
74
75 const taroConfigPath = path.join(homedir, TARO_CONFIG_FLODER)
76 const taroConfig = path.join(taroConfigPath, TARO_BASE_CONFIG)
77
78 if (fs.existsSync(taroConfig)) {
79 const config = await fs.readJSON(taroConfig)
80 templateSource = config && config.templateSource ? config.templateSource : DEFAULT_TEMPLATE_SRC
81 } else {
82 await fs.createFile(taroConfig)
83 await fs.writeJSON(taroConfig, { templateSource: DEFAULT_TEMPLATE_SRC })
84 templateSource = DEFAULT_TEMPLATE_SRC
85 }
86
87 // 从模板源下载模板
88 await fetchTemplate(templateSource, this.templatePath(''))
89 }
90
91 async create () {
92 const date = new Date()
93 this.getTemplateInfo()
94 this.conf.date = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
95
96 if (!fs.existsSync(this.templatePath(this.conf.template))) {
97 await this.fetchTemplates()
98 }
99
100 this.write()
101 }
102
103 write () {
104 createPage(this, this.conf, () => {
105 console.log(`${chalk.green('✔ ')}${chalk.grey(`创建页面 ${this.conf.pageName} 成功!`)}`)
106 }).catch(err => console.log(err))
107 }
108}
109
\No newline at end of file