forked from stenciljs/core
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgenerate-cjs.ts
67 lines (60 loc) · 2.17 KB
/
generate-cjs.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
import { generatePreamble, join, relativeImport } from '@utils';
import type { OutputOptions, RollupBuild } from 'rollup';
import type * as d from '../../../declarations';
import { generateRollupOutput } from '../../app-core/bundle-app-core';
import { generateLazyModules } from './generate-lazy-module';
export const generateCjs = async (
config: d.ValidatedConfig,
compilerCtx: d.CompilerCtx,
buildCtx: d.BuildCtx,
rollupBuild: RollupBuild,
outputTargets: d.OutputTargetDistLazy[],
): Promise<d.UpdatedLazyBuildCtx> => {
const cjsOutputs = outputTargets.filter((o) => !!o.cjsDir);
if (cjsOutputs.length > 0) {
const outputTargetType = cjsOutputs[0].type;
const esmOpts: OutputOptions = {
banner: generatePreamble(config),
format: 'cjs',
entryFileNames: '[name].cjs.js',
assetFileNames: '[name]-[hash][extname]',
sourcemap: config.sourceMap,
};
const results = await generateRollupOutput(rollupBuild, esmOpts, config, buildCtx.entryModules);
if (results != null) {
const destinations = cjsOutputs
.map((o) => o.cjsDir)
.filter((cjsDir): cjsDir is string => typeof cjsDir === 'string');
buildCtx.commonJsComponentBundle = await generateLazyModules(
config,
compilerCtx,
buildCtx,
outputTargetType,
destinations,
results,
'es2017',
false,
'.cjs',
);
await generateShortcuts(compilerCtx, results, cjsOutputs);
}
}
return { name: 'cjs', buildCtx };
};
const generateShortcuts = (
compilerCtx: d.CompilerCtx,
rollupResult: d.RollupResult[],
outputTargets: d.OutputTargetDistLazy[],
): Promise<void[]> => {
const indexFilename = rollupResult.find((r) => r.type === 'chunk' && r.isIndex).fileName;
return Promise.all(
outputTargets.map(async (o) => {
if (o.cjsIndexFile) {
const entryPointPath = join(o.cjsDir, indexFilename);
const relativePath = relativeImport(o.cjsIndexFile, entryPointPath);
const shortcutContent = `module.exports = require('${relativePath}');\n`;
await compilerCtx.fs.writeFile(o.cjsIndexFile, shortcutContent, { outputTargetType: o.type });
}
}),
);
};