/
cli.ts
115 lines (107 loc) · 2.75 KB
/
cli.ts
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
import { BundlerConfigType } from '@umijs/types';
import {
BabelRegister,
chalk,
compatESModuleRequire,
getFile,
portfinder,
rimraf,
yParser,
} from '@umijs/utils';
import { basename, extname, join } from 'path';
import { Server } from '@umijs/server';
import assert from 'assert';
import { existsSync } from 'fs';
import { Bundler } from './index';
import DevCompileDonePlugin from './DevCompileDonePlugin';
const args = yParser(process.argv.slice(2), {
alias: {
version: ['v'],
help: ['h'],
},
boolean: ['version'],
});
const command = args._[0];
const cwd = join(process.cwd(), args.cwd || '');
const env = args.env || (command === 'dev' ? 'development' : 'production');
process.env.NODE_ENV = env;
if (args.version && !command) {
args._[0] = 'version';
const local = existsSync(join(__dirname, '../.local'))
? chalk.cyan('@local')
: '';
console.log(`bundler-webpack@${require('../package.json').version}${local}`);
process.exit(0);
}
(async () => {
const configPath = join(cwd, args.config || 'config.ts');
const babelRegister = new BabelRegister();
babelRegister.setOnlyMap({
key: 'config',
value: [configPath],
});
const config = existsSync(configPath)
? compatESModuleRequire(require(configPath))
: {};
let entry: string = args.entry;
if (entry) {
entry = join(cwd, entry);
} else {
const files = [
getFile({
base: cwd,
fileNameWithoutExt: 'src/index',
type: 'javascript',
}),
getFile({
base: cwd,
fileNameWithoutExt: 'index',
type: 'javascript',
}),
].filter(Boolean);
assert(files.length, `Can't find the default entry.`);
entry = files[0]?.path!;
}
const bundler = new Bundler({
cwd,
config,
});
// @ts-ignore
const webpackConfig = await bundler.getConfig({
env,
type: BundlerConfigType.csr,
hot: args.hot,
entry: config.entry || {
[basename(entry, extname(entry))]: entry,
},
});
if (command === 'build') {
rimraf.sync(join(cwd, 'dist'));
const { stats } = await bundler.build({
bundleConfigs: [webpackConfig],
});
console.log(stats.toString('normal'));
} else if (command === 'dev') {
const port = await portfinder.getPortPromise({
port: 8000,
});
// @ts-ignore
webpackConfig.plugins!.push(new DevCompileDonePlugin({ port }));
const devServerOpts = bundler.setupDevServerOpts({
bundleConfigs: [webpackConfig],
});
const server = new Server({
...devServerOpts,
compress: true,
headers: {
'access-control-allow-origin': '*',
},
});
await server.listen({
port,
hostname: '127.0.0.1',
});
} else {
throw new Error(`Unsupported command ${command}.`);
}
})();