-
Notifications
You must be signed in to change notification settings - Fork 508
/
index.js
executable file
·310 lines (284 loc) · 9.01 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
#!/usr/bin/env node
import sade from 'sade';
import glob from 'tiny-glob/sync';
import { rollup, watch } from 'rollup';
import asyncro from 'asyncro';
import chalk from 'chalk';
import util from 'util';
import fs from 'fs-extra';
import jest from 'jest';
import logError from './logError';
import path from 'path';
import mkdirp from 'mkdirp';
import execa from 'execa';
import ora from 'ora';
import { paths } from './constants';
import * as Messages from './messages';
import { createRollupConfig } from './createRollupConfig';
import { createJestConfig } from './createJestConfig';
import { safeVariableName, resolveApp, safePackageName } from './utils';
import * as Output from './output';
import { concatAllArray } from 'jpjs';
const prog = sade('tsdx');
let appPackageJson;
try {
appPackageJson = fs.readJSONSync(resolveApp('package.json'));
} catch (e) {}
const stat = util.promisify(fs.stat);
export const isDir = name =>
stat(name)
.then(stats => stats.isDirectory())
.catch(() => false);
export const isFile = name =>
stat(name)
.then(stats => stats.isFile())
.catch(() => false);
async function jsOrTs(filename) {
const extension = (await isFile(resolveApp(filename + '.ts')))
? '.ts'
: (await isFile(resolveApp(filename + '.tsx')))
? '.tsx'
: '.js';
return resolveApp(`${filename}${extension}`);
}
async function getInputs(entries, source) {
let inputs = [];
let stub = [];
stub
.concat(
entries && entries.length
? entries
: (source && resolveApp(source)) ||
((await isDir(resolveApp('src'))) && (await jsOrTs('src/index')))
)
.map(file => glob(file))
.forEach(input => inputs.push(input));
return concatAllArray(inputs);
}
function createBuildConfigs(opts) {
return concatAllArray(
opts.input.map(input => [
opts.format.includes('cjs') &&
createRollupConfig('cjs', 'development', { ...opts, input }),
opts.format.includes('cjs') &&
createRollupConfig('cjs', 'production', { ...opts, input }),
opts.format.includes('es') &&
createRollupConfig('es', 'production', { ...opts, input }),
opts.format.includes('umd') &&
createRollupConfig('umd', 'development', { ...opts, input }),
opts.format.includes('umd') &&
createRollupConfig('umd', 'production', { ...opts, input }),
])
);
}
async function moveTypes() {
try {
// Move the typescript types to the base of the ./dist folder
await fs.copy(paths.appDist + '/src', paths.appDist, {
overwrite: true,
});
await fs.remove(paths.appDist + '/src');
} catch (e) {}
}
prog
.command('create <pkg>')
.describe('Create a new package with TSDX')
.action(async pkg => {
const bootSpinner = ora(`Creating ${chalk.bold.green(pkg)}...`).start();
try {
const projectPath = fs.realpathSync(process.cwd()) + '/' + pkg;
// copy the template
await fs.copy(path.resolve(__dirname, '../template'), projectPath, {
overwrite: true,
});
// fix gitignore
await fs.move(
path.resolve(projectPath, './gitignore'),
path.resolve(projectPath, './.gitignore')
);
// Install deps
process.chdir(projectPath);
const safeName = safePackageName(pkg);
const pkgJson = {
name: safeName,
version: '0.1.0',
main: 'dist/index.js',
'umd:main': `dist/${safeName}.umd.production.js`,
module: `dist/${safeName}.es.production.js`,
typings: 'dist/index.d.ts',
files: ['dist'],
scripts: {
start: 'tsdx watch',
build: 'tsdx build',
prepare: 'npm run build',
test: 'tsdx test',
},
};
await fs.outputJSON(path.resolve(projectPath, 'package.json'), pkgJson);
bootSpinner.succeed(`Created ${chalk.bold.green(pkg)}`);
Messages.start(pkg);
} catch (error) {
bootSpinner.fail(`Failed to create ${chalk.bold.red(pkg)}`);
logError(error);
process.exit(1);
}
const deps = ['@types/jest', 'tsdx', 'typescript'];
const installSpinner = ora(Messages.installing(deps)).start();
try {
await execa(`yarn`, ['add', ...deps, '--dev']);
installSpinner.succeed('Installed dependecines');
console.log(Messages.start(pkg));
} catch (error) {
installSpinner.fail('Failed to install dependencies');
logError(error);
process.exit(1);
}
});
prog
.command('watch')
.describe('Rebuilds on any change')
.option('--entry, -i', 'Entry module(s)')
.example('watch --entry src/foo.tsx')
.option('--target', 'Specify your target environment', 'web')
.example('watch --target node')
.option('--name', 'Specify name exposed in UMD builds')
.example('watch --name Foo')
.option('--format', 'Specify module format(s)', 'cjs,es,umd')
.example('watch --format cjs,es')
.action(async opts => {
opts.name = opts.name || appPackageJson.name;
opts.input = await getInputs(opts.entry, appPackageJson.source);
const [cjsDev, cjsProd, ...otherConfigs] = createBuildConfigs(opts);
if (opts.format.includes('cjs')) {
try {
await fs.writeFile(
resolveApp('dist/index.js'),
`
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./${safeVariableName(
opts.name
)}.cjs.production.js')
} else {
module.exports = require('./${safeVariableName(
opts.name
)}.cjs.development.js')
}`,
{
overwrite: true,
}
);
} catch (e) {}
}
await watch(
[cjsDev, cjsProd, ...otherConfigs].map(inputOptions => ({
watch: {
silent: true,
include: 'src/**',
exclude: 'node_modules/**',
},
...inputOptions,
}))
).on('event', async event => {
if (event.code === 'ERROR') {
logError(event.error);
}
if (event.code === 'FATAL') {
logError(event.error);
}
if (event.code === 'END') {
try {
await moveTypes();
} catch (_error) {}
}
});
});
prog
.command('build')
.describe('Build your project once and exit')
.option('--entry, -i', 'Entry module(s)')
.example('build --entry src/foo.tsx')
.option('--target', 'Specify your target environment', 'web')
.example('build --target node')
.option('--name', 'Specify name exposed in UMD builds')
.example('build --name Foo')
.option('--format', 'Specify module format(s)', 'cjs,es,umd')
.example('build --format cjs,es')
.action(async opts => {
opts.name = opts.name || appPackageJson.name;
opts.input = await getInputs(opts.entry, appPackageJson.source);
const [cjsDev, cjsProd, ...otherConfigs] = createBuildConfigs(opts);
if (opts.format.includes('cjs')) {
try {
await fs.writeFile(
resolveApp('dist/index.js'),
`
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./${safeVariableName(
opts.name
)}.cjs.production.js')
} else {
module.exports = require('./${safeVariableName(
opts.name
)}.cjs.development.js')
}`,
{
overwrite: true,
}
);
} catch (e) {}
}
try {
await asyncro.map(
[cjsDev, cjsProd, ...otherConfigs],
async inputOptions => {
let bundle = await rollup(inputOptions);
await bundle.write(inputOptions.output);
}
);
await moveTypes();
} catch (error) {
logError(error);
}
});
prog
.command('test')
.describe(
'Run jest test runner in watch mode. Passes through all flags directly to Jest'
)
.action(async opts => {
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
throw err;
});
const argv = process.argv.slice(2);
// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
// Use Jest --watchAll flag (instead of) --watch as of Jest 23+
// @see https://github.com/wmonk/create-react-app-typescript/issues/282#issuecomment-379660648
argv.push('--watchAll');
}
const maybeTestSetupFiledExists = await fs.exists(paths.testsSetup);
const setupTestsFile = maybeTestSetupFiledExists
? '<rootDir>/src/setupTests.ts'
: undefined;
argv.push(
'--config',
JSON.stringify({
...createJestConfig(
relativePath => path.resolve(__dirname, '..', relativePath),
paths.appRoot
),
...appPackageJson.jest,
})
);
const [_skipTheWordTest, ...argsToPassToJestCli] = argv;
jest.run(argsToPassToJestCli);
});
prog.parse(process.argv);