/
lazy-output.ts
168 lines (149 loc) · 6.42 KB
/
lazy-output.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
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
import * as d from '../../../declarations';
import type { BundleOptions } from '../../bundle/bundle-interface';
import { bundleOutput } from '../../bundle/bundle-output';
import { catchError } from '@utils';
import { generateEntryModules } from '../../entries/entry-modules';
import { getLazyBuildConditionals } from './lazy-build-conditionals';
import { isOutputTargetDistLazy, isOutputTargetDist } from '../output-utils';
import {
LAZY_BROWSER_ENTRY_ID,
LAZY_EXTERNAL_ENTRY_ID,
STENCIL_APP_GLOBALS_ID,
STENCIL_CORE_ID,
STENCIL_INTERNAL_CLIENT_PATCH_BROWSER_ID,
STENCIL_INTERNAL_CLIENT_PATCH_ESM_ID,
USER_INDEX_ENTRY_ID,
} from '../../bundle/entry-alias-ids';
import { lazyComponentTransform } from '../../transformers/component-lazy/transform-lazy-component';
import { generateCjs } from './generate-cjs';
import { generateEsmBrowser } from './generate-esm-browser';
import { generateEsm } from './generate-esm';
import { generateSystem } from './generate-system';
import { generateModuleGraph } from '../../entries/component-graph';
import { removeCollectionImports } from '../../transformers/remove-collection-imports';
import { updateStencilCoreImports } from '../../transformers/update-stencil-core-import';
import MagicString from 'magic-string';
export const outputLazy = async (config: d.Config, compilerCtx: d.CompilerCtx, buildCtx: d.BuildCtx) => {
const outputTargets = config.outputTargets.filter(isOutputTargetDistLazy);
if (outputTargets.length === 0) {
return;
}
const timespan = buildCtx.createTimeSpan(`generate lazy started`);
try {
// const criticalBundles = getCriticalPath(buildCtx);
const bundleOpts: BundleOptions = {
id: 'lazy',
platform: 'client',
conditionals: getLazyBuildConditionals(config, buildCtx.components),
customTransformers: getLazyCustomTransformer(config, compilerCtx),
inlineWorkers: config.outputTargets.some(isOutputTargetDist),
inputs: {
[config.fsNamespace]: LAZY_BROWSER_ENTRY_ID,
loader: LAZY_EXTERNAL_ENTRY_ID,
index: USER_INDEX_ENTRY_ID,
},
loader: {
[LAZY_EXTERNAL_ENTRY_ID]: getLazyEntry(false),
[LAZY_BROWSER_ENTRY_ID]: getLazyEntry(true),
},
};
// we've got the compiler context filled with app modules and collection dependency modules
// figure out how all these components should be connected
generateEntryModules(config, buildCtx);
buildCtx.entryModules.forEach(entryModule => {
bundleOpts.inputs[entryModule.entryKey] = entryModule.entryKey;
});
const rollupBuild = await bundleOutput(config, compilerCtx, buildCtx, bundleOpts);
if (rollupBuild != null) {
const [componentBundle] = await Promise.all([
generateEsmBrowser(config, compilerCtx, buildCtx, rollupBuild, outputTargets),
generateEsm(config, compilerCtx, buildCtx, rollupBuild, outputTargets),
generateSystem(config, compilerCtx, buildCtx, rollupBuild, outputTargets),
generateCjs(config, compilerCtx, buildCtx, rollupBuild, outputTargets),
]);
await generateLegacyLoader(config, compilerCtx, outputTargets);
if (componentBundle != null) {
buildCtx.componentGraph = generateModuleGraph(buildCtx.components, componentBundle);
}
}
} catch (e) {
catchError(buildCtx.diagnostics, e);
}
timespan.finish(`generate lazy finished`);
};
const getLazyCustomTransformer = (config: d.Config, compilerCtx: d.CompilerCtx) => {
const transformOpts: d.TransformOptions = {
coreImportPath: STENCIL_CORE_ID,
componentExport: 'lazy',
componentMetadata: null,
currentDirectory: config.sys.getCurrentDirectory(),
proxy: null,
style: 'static',
styleImportData: 'queryparams',
};
return [updateStencilCoreImports(transformOpts.coreImportPath), lazyComponentTransform(compilerCtx, transformOpts), removeCollectionImports(compilerCtx)];
};
const getLazyEntry = (isBrowser: boolean) => {
const s = new MagicString(``);
s.append(`import { bootstrapLazy } from '${STENCIL_CORE_ID}';\n`);
if (isBrowser) {
s.append(`import { patchBrowser } from '${STENCIL_INTERNAL_CLIENT_PATCH_BROWSER_ID}';\n`);
s.append(`import { globalScripts } from '${STENCIL_APP_GLOBALS_ID}';\n`);
s.append(`patchBrowser().then(options => {\n`);
s.append(` globalScripts();\n`);
s.append(` return bootstrapLazy([/*!__STENCIL_LAZY_DATA__*/], options);\n`);
s.append(`});\n`);
} else {
s.append(`import { patchEsm } from '${STENCIL_INTERNAL_CLIENT_PATCH_ESM_ID}';\n`);
s.append(`import { globalScripts } from '${STENCIL_APP_GLOBALS_ID}';\n`);
s.append(`export const defineCustomElements = (win, options) => {\n`);
s.append(` if (typeof window === 'undefined') return Promise.resolve();\n`);
s.append(` return patchEsm().then(() => {\n`);
s.append(` globalScripts();\n`);
s.append(` return bootstrapLazy([/*!__STENCIL_LAZY_DATA__*/], options);\n`);
s.append(` });\n`);
s.append(`};\n`);
}
return s.toString();
};
const generateLegacyLoader = (config: d.Config, compilerCtx: d.CompilerCtx, outputTargets: d.OutputTargetDistLazy[]) => {
return Promise.all(
outputTargets.map(async o => {
if (o.legacyLoaderFile) {
const loaderContent = getLegacyLoader(config);
await compilerCtx.fs.writeFile(o.legacyLoaderFile, loaderContent, { outputTargetType: o.type });
}
}),
);
};
const getLegacyLoader = (config: d.Config) => {
const namespace = config.fsNamespace;
return `
(function(doc){
var scriptElm = doc.scripts[doc.scripts.length - 1];
var warn = ['[${namespace}] Deprecated script, please remove: ' + scriptElm.outerHTML];
warn.push('To improve performance it is recommended to set the differential scripts in the head as follows:')
var parts = scriptElm.src.split('/');
parts.pop();
parts.push('${namespace}');
var url = parts.join('/');
var scriptElm = doc.createElement('script');
scriptElm.setAttribute('type', 'module');
scriptElm.src = url + '/${namespace}.esm.js';
warn.push(scriptElm.outerHTML);
scriptElm.setAttribute('data-stencil-namespace', '${namespace}');
doc.head.appendChild(scriptElm);
${
config.buildEs5 &&
`
scriptElm = doc.createElement('script');
scriptElm.setAttribute('nomodule', '');
scriptElm.src = url + '/${namespace}.js';
warn.push(scriptElm.outerHTML);
scriptElm.setAttribute('data-stencil-namespace', '${namespace}');
doc.head.appendChild(scriptElm)
`
}
console.warn(warn.join('\\n'));
})(document);`;
};