UNPKG

6.57 kBJavaScriptView Raw
1'use strict';
2
3process.on('unhandledRejection', err => {
4 throw err;
5});
6
7const fs = require('fs-extra');
8const path = require('path');
9const chalk = require('chalk');
10const execSync = require('child_process').execSync;
11const spawn = require('react-dev-utils/crossSpawn');
12const os = require('os');
13const scriptVersion = require("../package").version;
14function isInGitRepository() {
15 try {
16 execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
17 return true;
18 } catch (e) {
19 return false;
20 }
21}
22
23function isInMercurialRepository() {
24 try {
25 execSync('hg --cwd . root', { stdio: 'ignore' });
26 return true;
27 } catch (e) {
28 return false;
29 }
30}
31
32function tryGitInit(appPath) {
33 let didInit = false;
34 try {
35 execSync('git --version', { stdio: 'ignore' });
36 if (isInGitRepository() || isInMercurialRepository()) {
37 return false;
38 }
39
40 execSync('git init', { stdio: 'ignore' });
41 didInit = true;
42
43 execSync('git add -A', { stdio: 'ignore' });
44 execSync('git commit -m "Initial commit from @mogul/create-mogul-app"', {
45 stdio: 'ignore',
46 });
47 return true;
48 } catch (e) {
49 if (didInit) {
50 // If we successfully initialized but couldn't commit,
51 // maybe the commit author config is not set.
52 // In the future, we might supply our own committer
53 // like Ember CLI does, but for now, let's just
54 // remove the Git files to avoid a half-done state.
55 try {
56 // unlinkSync() doesn't work on directories.
57 fs.removeSync(path.join(appPath, '.git'));
58 } catch (removeErr) {
59 // Ignore.
60 }
61 }
62 return false;
63 }
64}
65
66module.exports = function(
67 appPath,
68 appName,
69 verbose,
70 originalDirectory,
71 template
72) {
73 const ownPackageName = require(path.join(__dirname, '..', 'package.json'))
74 .name;
75 const ownPath = path.join(appPath, 'node_modules', ownPackageName);
76 const appPackage = require(path.join(appPath, 'package.json'));
77 const useYarn = fs.existsSync(path.join(appPath, 'yarn.lock'));
78
79 // Copy over some of the devDependencies
80 appPackage.dependencies = appPackage.dependencies || {};
81
82 // Setup the script rules
83 appPackage.scripts = Object.assign({}, appPackage.scripts,{
84 start: 'create-mogul-app start',
85 build: 'create-mogul-app build',
86 "server:mock": "json-server --watch mock/index.js --port 3004"
87 });
88 //添加 example 代理
89 appPackage.proxy = {
90 "/example": {
91 "target": "http://localhost:3004",
92 "secure": false,
93 "changeOrigin": true,
94 "pathRewrite": {
95 "^/example": ""
96 }
97 }
98 };
99
100 fs.writeFileSync(
101 path.join(appPath, 'package.json'),
102 JSON.stringify(appPackage, null, 2) + os.EOL
103 );
104
105 const readmeExists = fs.existsSync(path.join(appPath, 'README.md'));
106 if (readmeExists) {
107 fs.renameSync(
108 path.join(appPath, 'README.md'),
109 path.join(appPath, 'README.old.md')
110 );
111 }
112
113 // Copy the files for the user
114 const templatePath = template
115 ? path.resolve(originalDirectory, template)
116 : path.join(ownPath, 'template');
117 if (fs.existsSync(templatePath)) {
118 fs.copySync(templatePath, appPath);
119 } else {
120 console.error(
121 `Could not locate supplied template: ${chalk.green(templatePath)}`
122 );
123 return;
124 }
125
126 // Rename gitignore after the fact to prevent npm from renaming it to .npmignore
127 // See: https://github.com/npm/npm/issues/1862
128 try {
129 fs.moveSync(
130 path.join(appPath, 'gitignore'),
131 path.join(appPath, '.gitignore'),
132 []
133 );
134 } catch (err) {
135 // Append if there's already a `.gitignore` file there
136 if (err.code === 'EEXIST') {
137 const data = fs.readFileSync(path.join(appPath, 'gitignore'));
138 fs.appendFileSync(path.join(appPath, '.gitignore'), data);
139 fs.unlinkSync(path.join(appPath, 'gitignore'));
140 } else {
141 throw err;
142 }
143 }
144
145// let command;
146// let args;
147
148// if (useYarn) {
149// command = 'yarnpkg';
150// args = ['add', "--dev"];
151// } else {
152// command = 'npm';
153// args = ['install', '--save', verbose && '--verbose'].filter(e => e);
154// }
155
156 // Install additional template dependencies, if present
157// const templateDependenciesPath = path.join(
158// ownPath,
159// '.template.dependencies.json'
160// );
161//
162// if (fs.existsSync(templateDependenciesPath)) {
163// const templateDependencies = require(templateDependenciesPath).dependencies;
164// args = args.concat(
165// Object.keys(templateDependencies).map(key => {
166// return `${key}@${templateDependencies[key]}`;
167// })
168// );
169// fs.unlinkSync(templateDependenciesPath);
170//
171// console.log(`Installing template dev dependencies using ${command}...`);
172// console.log();
173//
174// const proc = spawn.sync(command, args, { stdio: 'inherit' });
175// if (proc.status !== 0) {
176// console.error(`\`${command} ${args.join(' ')}\` failed`);
177// return;
178// }
179// }
180
181 if (tryGitInit(appPath)) {
182 console.log();
183 console.log('Initialized a git repository.');
184 }
185
186 // Display the most elegant way to cd.
187 // This needs to handle an undefined originalDirectory for
188 // backward compatibility with old global-cli's.
189 let cdpath;
190 if (originalDirectory && path.join(originalDirectory, appName) === appPath) {
191 cdpath = appName;
192 } else {
193 cdpath = appPath;
194 }
195
196 // Change displayed command to yarn instead of yarnpkg
197 const displayedCommand = useYarn ? 'yarn' : 'npm';
198
199 console.log();
200 console.log(`Success! Created ${appName} at ${appPath}`);
201 console.log('Inside that directory, you can run several commands:');
202 console.log();
203 console.log(chalk.cyan(` ${displayedCommand} start`));
204 console.log(' Starts the development server.');
205 console.log();
206 console.log(
207 chalk.cyan(` ${displayedCommand} ${useYarn ? '' : 'run '}build`)
208 );
209 console.log(' Bundles the app into static files for production.');
210 console.log();
211 console.log('We suggest that you begin by typing:');
212 console.log();
213 console.log(chalk.cyan(' cd'), cdpath);
214 console.log(` ${chalk.cyan(`${displayedCommand} start`)}`);
215 if (readmeExists) {
216 console.log();
217 console.log(
218 chalk.yellow(
219 'You had a `README.md` file, we renamed it to `README.old.md`'
220 )
221 );
222 }
223 console.log();
224 console.log(chalk.cyan(`食行生鲜运营平台开发部出品 version:${ scriptVersion }`));
225};
226
227function isReactInstalled(appPackage) {
228 const dependencies = appPackage.dependencies || {};
229
230 return (
231 typeof dependencies.react !== 'undefined' &&
232 typeof dependencies['react-dom'] !== 'undefined'
233 );
234}