UNPKG

2.85 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 const pkgPath = path.join(projectDir, 'package.json')
44 if (fs.existsSync(pkgPath)) {
45 return pkgPath
46 }
47 return path.join(projectDir, 'client', 'package.json')
48 }
49
50 getTemplateInfo () {
51 const pkg = fs.readJSONSync(this.getPkgPath())
52 const templateInfo = pkg.templateInfo || {
53 name: 'default',
54 css: 'none',
55 typescript: false
56 }
57 templateInfo.template = templateInfo.name
58 delete templateInfo.name
59 this.conf = Object.assign(this.conf, templateInfo)
60 }
61
62 async fetchTemplates () {
63 const homedir = getUserHomeDir()
64 let templateSource = DEFAULT_TEMPLATE_SRC
65 if (!homedir) chalk.yellow('找不到用户根目录,使用默认模版源!')
66
67 const taroConfigPath = path.join(homedir, TARO_CONFIG_FLODER)
68 const taroConfig = path.join(taroConfigPath, TARO_BASE_CONFIG)
69
70 if (fs.existsSync(taroConfig)) {
71 const config = await fs.readJSON(taroConfig)
72 templateSource = config && config.templateSource ? config.templateSource : DEFAULT_TEMPLATE_SRC
73 } else {
74 await fs.createFile(taroConfig)
75 await fs.writeJSON(taroConfig, { templateSource: DEFAULT_TEMPLATE_SRC })
76 templateSource = DEFAULT_TEMPLATE_SRC
77 }
78
79 // 从模板源下载模板
80 await fetchTemplate(templateSource, this.templatePath(''))
81 }
82
83 async create () {
84 const date = new Date()
85 this.getTemplateInfo()
86 this.conf.date = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
87
88 if (!fs.existsSync(this.templatePath(this.conf.template))) {
89 await this.fetchTemplates()
90 }
91
92 this.write()
93 }
94
95 write () {
96 createPage(this, this.conf, () => {
97 console.log(`${chalk.green('✔ ')}${chalk.grey(`创建页面 ${this.conf.pageName} 成功!`)}`)
98 }).catch(err => console.log(err))
99 }
100}
101
\No newline at end of file