/
Module.ts
868 lines (774 loc) · 25.8 KB
/
Module.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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
import * as acorn from 'acorn';
import * as ESTree from 'estree';
import { locate } from 'locate-character';
import MagicString from 'magic-string';
import extractAssignedNames from 'rollup-pluginutils/src/extractAssignedNames';
import ClassDeclaration from './ast/nodes/ClassDeclaration';
import ExportAllDeclaration from './ast/nodes/ExportAllDeclaration';
import ExportDefaultDeclaration from './ast/nodes/ExportDefaultDeclaration';
import ExportNamedDeclaration from './ast/nodes/ExportNamedDeclaration';
import FunctionDeclaration from './ast/nodes/FunctionDeclaration';
import Identifier from './ast/nodes/Identifier';
import Import from './ast/nodes/Import';
import ImportDeclaration from './ast/nodes/ImportDeclaration';
import ImportSpecifier from './ast/nodes/ImportSpecifier';
import { nodeConstructors } from './ast/nodes/index';
import Literal from './ast/nodes/Literal';
import MetaProperty from './ast/nodes/MetaProperty';
import * as NodeType from './ast/nodes/NodeType';
import Program from './ast/nodes/Program';
import { Node, NodeBase } from './ast/nodes/shared/Node';
import TemplateLiteral from './ast/nodes/TemplateLiteral';
import VariableDeclaration from './ast/nodes/VariableDeclaration';
import ModuleScope from './ast/scopes/ModuleScope';
import { EntityPathTracker } from './ast/utils/EntityPathTracker';
import { UNKNOWN_PATH } from './ast/values';
import ExportShimVariable from './ast/variables/ExportShimVariable';
import ExternalVariable from './ast/variables/ExternalVariable';
import NamespaceVariable from './ast/variables/NamespaceVariable';
import Variable from './ast/variables/Variable';
import Chunk from './Chunk';
import ExternalModule from './ExternalModule';
import Graph from './Graph';
import {
Asset,
DecodedSourceMapOrMissing,
EmittedChunk,
ExistingDecodedSourceMap,
ModuleJSON,
ResolvedIdMap,
RollupError,
RollupWarning,
TransformModuleJSON
} from './rollup/types';
import { error } from './utils/error';
import getCodeFrame from './utils/getCodeFrame';
import { getOriginalLocation } from './utils/getOriginalLocation';
import { makeLegal } from './utils/identifierHelpers';
import { basename, extname } from './utils/path';
import { markPureCallExpressions } from './utils/pureComments';
import relativeId from './utils/relativeId';
import { RenderOptions } from './utils/renderHelpers';
import { SOURCEMAPPING_URL_RE } from './utils/sourceMappingURL';
import { timeEnd, timeStart } from './utils/timers';
import { markModuleAndImpureDependenciesAsExecuted } from './utils/traverseStaticDependencies';
import { MISSING_EXPORT_SHIM_VARIABLE } from './utils/variableNames';
export interface CommentDescription {
block: boolean;
end: number;
start: number;
text: string;
}
export interface ImportDescription {
module: Module | ExternalModule | null;
name: string;
source: string;
start: number;
}
export interface ExportDescription {
identifier: string | null;
localName: string;
}
export interface ReexportDescription {
localName: string;
module: Module;
source: string;
start: number;
}
export interface AstContext {
addDynamicImport: (node: Import) => void;
addExport: (
node: ExportAllDeclaration | ExportNamedDeclaration | ExportDefaultDeclaration
) => void;
addImport: (node: ImportDeclaration) => void;
addImportMeta: (node: MetaProperty) => void;
annotations: boolean;
code: string;
deoptimizationTracker: EntityPathTracker;
error: (props: RollupError, pos: number) => void;
fileName: string;
getAssetFileName: (assetReferenceId: string) => string;
getChunkFileName: (chunkReferenceId: string) => string;
getExports: () => string[];
getModuleExecIndex: () => number;
getModuleName: () => string;
getReexports: () => string[];
importDescriptions: { [name: string]: ImportDescription };
includeDynamicImport: (node: Import) => void;
includeVariable: (variable: Variable) => void;
isCrossChunkImport: (importDescription: ImportDescription) => boolean;
magicString: MagicString;
module: Module; // not to be used for tree-shaking
moduleContext: string;
nodeConstructors: { [name: string]: typeof NodeBase };
preserveModules: boolean;
propertyReadSideEffects: boolean;
traceExport: (name: string) => Variable;
traceVariable: (name: string) => Variable | null;
treeshake: boolean;
tryCatchDeoptimization: boolean;
usesTopLevelAwait: boolean;
warn: (warning: RollupWarning, pos: number) => void;
}
export const defaultAcornOptions: acorn.Options = {
ecmaVersion: 2019,
preserveParens: false,
sourceType: 'module'
};
function tryParse(module: Module, Parser: typeof acorn.Parser, acornOptions: acorn.Options) {
try {
return Parser.parse(module.code, {
...defaultAcornOptions,
...acornOptions,
onComment: (block: boolean, text: string, start: number, end: number) =>
module.comments.push({ block, text, start, end })
});
} catch (err) {
let message = err.message.replace(/ \(\d+:\d+\)$/, '');
if (module.id.endsWith('.json')) {
message += ' (Note that you need rollup-plugin-json to import JSON files)';
} else if (!module.id.endsWith('.js')) {
message += ' (Note that you need plugins to import files that are not JavaScript)';
}
module.error(
{
code: 'PARSE_ERROR',
message
},
err.pos
);
}
}
function handleMissingExport(
exportName: string,
importingModule: Module,
importedModule: string,
importerStart?: number
) {
importingModule.error(
{
code: 'MISSING_EXPORT',
message: `'${exportName}' is not exported by ${relativeId(importedModule)}`,
url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module-`
},
importerStart as number
);
}
const MISSING_EXPORT_SHIM_DESCRIPTION: ExportDescription = {
identifier: null,
localName: MISSING_EXPORT_SHIM_VARIABLE
};
export default class Module {
chunk?: Chunk;
chunkAlias: string = null as any;
code!: string;
comments: CommentDescription[] = [];
customTransformCache!: boolean;
dependencies: (Module | ExternalModule)[] = [];
dynamicallyImportedBy: Module[] = [];
dynamicDependencies: (Module | ExternalModule)[] = [];
dynamicImports: {
node: Import;
resolution: Module | ExternalModule | string | null;
}[] = [];
entryPointsHash: Uint8Array = new Uint8Array(10);
excludeFromSourcemap: boolean;
execIndex = Infinity;
exportAllModules: (Module | ExternalModule)[] = null as any;
exportAllSources: string[] = [];
exports: { [name: string]: ExportDescription } = Object.create(null);
exportsAll: { [name: string]: string } = Object.create(null);
exportShimVariable: ExportShimVariable = new ExportShimVariable(this);
facadeChunk: Chunk | null = null;
id: string;
importDescriptions: { [name: string]: ImportDescription } = Object.create(null);
importMetas: MetaProperty[] = [];
imports = new Set<Variable>();
isEntryPoint: boolean;
isExecuted = false;
isUserDefinedEntryPoint = false;
manualChunkAlias: string = null as any;
moduleSideEffects: boolean;
originalCode!: string;
originalSourcemap!: ExistingDecodedSourceMap | null;
reexports: { [name: string]: ReexportDescription } = Object.create(null);
resolvedIds!: ResolvedIdMap;
scope!: ModuleScope;
sourcemapChain!: DecodedSourceMapOrMissing[];
sources: string[] = [];
transformAssets?: Asset[];
transformChunks?: EmittedChunk[];
usesTopLevelAwait = false;
private allExportNames?: Set<string>;
private ast!: Program;
private astContext!: AstContext;
private context: string;
private esTreeAst!: ESTree.Program;
private graph: Graph;
private magicString!: MagicString;
private namespaceVariable: NamespaceVariable = undefined as any;
private transformDependencies: string[] | null = null;
private transitiveReexports?: string[];
constructor(graph: Graph, id: string, moduleSideEffects: boolean, isEntry: boolean) {
this.id = id;
this.graph = graph;
this.excludeFromSourcemap = /\0/.test(id);
this.context = graph.getModuleContext(id);
this.moduleSideEffects = moduleSideEffects;
this.isEntryPoint = isEntry;
}
basename() {
const base = basename(this.id);
const ext = extname(this.id);
return makeLegal(ext ? base.slice(0, -ext.length) : base);
}
bindReferences() {
this.ast.bind();
}
error(props: RollupError, pos: number) {
if (pos !== undefined) {
props.pos = pos;
let location = locate(this.code, pos, { offsetLine: 1 });
try {
location = getOriginalLocation(this.sourcemapChain, location);
} catch (e) {
this.warn(
{
code: 'SOURCEMAP_ERROR',
loc: {
column: location.column,
file: this.id,
line: location.line
},
message: `Error when using sourcemap for reporting an error: ${e.message}`,
pos
},
undefined as any
);
}
props.loc = {
column: location.column,
file: this.id,
line: location.line
};
props.frame = getCodeFrame(this.originalCode, location.line, location.column);
}
error(props);
}
getAllExportNames(): Set<string> {
if (this.allExportNames) {
return this.allExportNames;
}
const allExportNames = (this.allExportNames = new Set<string>());
for (const name of Object.keys(this.exports)) {
allExportNames.add(name);
}
for (const name of Object.keys(this.reexports)) {
allExportNames.add(name);
}
for (const module of this.exportAllModules) {
if (module instanceof ExternalModule) {
allExportNames.add(`*${module.id}`);
continue;
}
for (const name of module.getAllExportNames()) {
if (name !== 'default') allExportNames.add(name);
}
}
return allExportNames;
}
getDynamicImportExpressions(): (string | Node)[] {
return this.dynamicImports.map(({ node }) => {
const importArgument = node.parent.arguments[0];
if (
importArgument instanceof TemplateLiteral &&
importArgument.quasis.length === 1 &&
importArgument.quasis[0].value.cooked
) {
return importArgument.quasis[0].value.cooked;
}
if (importArgument instanceof Literal && typeof importArgument.value === 'string') {
return importArgument.value;
}
return importArgument;
});
}
getExportNamesByVariable(): Map<Variable, string[]> {
const exportNamesByVariable: Map<Variable, string[]> = new Map();
for (const exportName of this.getAllExportNames()) {
const tracedVariable = this.getVariableForExportName(exportName);
if (
!tracedVariable ||
!(tracedVariable.included || tracedVariable instanceof ExternalVariable)
) {
continue;
}
const existingExportNames = exportNamesByVariable.get(tracedVariable);
if (existingExportNames) {
existingExportNames.push(exportName);
} else {
exportNamesByVariable.set(tracedVariable, [exportName]);
}
}
return exportNamesByVariable;
}
getExports() {
return Object.keys(this.exports);
}
getOrCreateNamespace(): NamespaceVariable {
return (
this.namespaceVariable || (this.namespaceVariable = new NamespaceVariable(this.astContext))
);
}
getReexports(): string[] {
if (this.transitiveReexports) {
return this.transitiveReexports;
}
// to avoid infinite recursion when using circular `export * from X`
this.transitiveReexports = [];
const reexports = new Set<string>();
for (const name in this.reexports) {
reexports.add(name);
}
for (const module of this.exportAllModules) {
if (module instanceof ExternalModule) {
reexports.add(`*${module.id}`);
} else {
for (const name of module.getExports().concat(module.getReexports())) {
if (name !== 'default') reexports.add(name);
}
}
}
return (this.transitiveReexports = Array.from(reexports));
}
getRenderedExports() {
// only direct exports are counted here, not reexports at all
const renderedExports: string[] = [];
const removedExports: string[] = [];
for (const exportName in this.exports) {
const variable = this.getVariableForExportName(exportName);
(variable && variable.included ? renderedExports : removedExports).push(exportName);
}
return { renderedExports, removedExports };
}
getTransitiveDependencies() {
return this.dependencies.concat(
this.getReexports().map(
exportName => this.getVariableForExportName(exportName).module as Module
)
);
}
getVariableForExportName(name: string, isExportAllSearch?: boolean): Variable {
if (name[0] === '*') {
if (name.length === 1) {
return this.getOrCreateNamespace();
} else {
// export * from 'external'
const module = this.graph.moduleById.get(name.slice(1)) as ExternalModule;
return module.getVariableForExportName('*');
}
}
// export { foo } from './other'
const reexportDeclaration = this.reexports[name];
if (reexportDeclaration) {
const declaration = reexportDeclaration.module.getVariableForExportName(
reexportDeclaration.localName
);
if (!declaration) {
handleMissingExport(
reexportDeclaration.localName,
this,
reexportDeclaration.module.id,
reexportDeclaration.start
);
}
return declaration;
}
const exportDeclaration = this.exports[name];
if (exportDeclaration) {
if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
return this.exportShimVariable;
}
const name = exportDeclaration.localName;
return this.traceVariable(name) || this.graph.scope.findVariable(name);
}
if (name !== 'default') {
for (const module of this.exportAllModules) {
const declaration = module.getVariableForExportName(name, true);
if (declaration) return declaration;
}
}
// we don't want to create shims when we are just
// probing export * modules for exports
if (this.graph.shimMissingExports && !isExportAllSearch) {
this.shimMissingExport(name);
return this.exportShimVariable;
}
return undefined as any;
}
include(): void {
if (this.ast.shouldBeIncluded()) this.ast.include(false);
}
includeAllExports() {
if (!this.isExecuted) {
this.graph.needsTreeshakingPass = true;
markModuleAndImpureDependenciesAsExecuted(this);
}
for (const exportName of this.getExports()) {
const variable = this.getVariableForExportName(exportName);
variable.deoptimizePath(UNKNOWN_PATH);
if (!variable.included) {
variable.include();
this.graph.needsTreeshakingPass = true;
}
}
for (const name of this.getReexports()) {
const variable = this.getVariableForExportName(name);
variable.deoptimizePath(UNKNOWN_PATH);
if (!variable.included) {
variable.include();
this.graph.needsTreeshakingPass = true;
}
if (variable instanceof ExternalVariable) {
variable.module.reexported = true;
}
}
}
includeAllInBundle() {
this.ast.include(true);
}
isIncluded() {
return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
}
linkDependencies() {
for (const source of this.sources) {
const id = this.resolvedIds[source].id;
if (id) {
const module = this.graph.moduleById.get(id);
this.dependencies.push(module as Module);
}
}
for (const { resolution } of this.dynamicImports) {
if (resolution instanceof Module || resolution instanceof ExternalModule) {
this.dynamicDependencies.push(resolution);
}
}
this.addModulesToSpecifiers(this.importDescriptions);
this.addModulesToSpecifiers(this.reexports);
this.exportAllModules = this.exportAllSources
.map(source => {
const id = this.resolvedIds[source].id;
return this.graph.moduleById.get(id) as Module | ExternalModule;
})
.sort((moduleA, moduleB) => {
const aExternal = moduleA instanceof ExternalModule;
const bExternal = moduleB instanceof ExternalModule;
return aExternal === bExternal ? 0 : aExternal ? 1 : -1;
});
}
render(options: RenderOptions): MagicString {
const magicString = this.magicString.clone();
this.ast.render(magicString, options);
this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
return magicString;
}
setSource({
ast,
code,
customTransformCache,
moduleSideEffects,
originalCode,
originalSourcemap,
resolvedIds,
sourcemapChain,
transformAssets,
transformChunks,
transformDependencies
}: TransformModuleJSON & {
transformAssets?: Asset[] | undefined;
transformChunks?: EmittedChunk[] | undefined;
}) {
this.code = code;
this.originalCode = originalCode;
this.originalSourcemap = originalSourcemap;
this.sourcemapChain = sourcemapChain;
if (transformAssets) {
this.transformAssets = transformAssets;
}
if (transformChunks) {
this.transformChunks = transformChunks;
}
this.transformDependencies = transformDependencies;
this.customTransformCache = customTransformCache;
if (typeof moduleSideEffects === 'boolean') {
this.moduleSideEffects = moduleSideEffects;
}
timeStart('generate ast', 3);
this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions);
markPureCallExpressions(this.comments, this.esTreeAst);
timeEnd('generate ast', 3);
this.resolvedIds = resolvedIds || Object.create(null);
// By default, `id` is the file name. Custom resolvers and loaders
// can change that, but it makes sense to use it for the source file name
const fileName = this.id;
this.magicString = new MagicString(code, {
filename: (this.excludeFromSourcemap ? null : fileName) as string, // don't include plugin helpers in sourcemap
indentExclusionRanges: []
});
this.removeExistingSourceMap();
timeStart('analyse ast', 3);
this.astContext = {
addDynamicImport: this.addDynamicImport.bind(this),
addExport: this.addExport.bind(this),
addImport: this.addImport.bind(this),
addImportMeta: this.addImportMeta.bind(this),
annotations: (this.graph.treeshakingOptions &&
this.graph.treeshakingOptions.annotations) as boolean,
code, // Only needed for debugging
deoptimizationTracker: this.graph.deoptimizationTracker,
error: this.error.bind(this),
fileName, // Needed for warnings
getAssetFileName: this.graph.pluginDriver.getAssetFileName,
getChunkFileName: this.graph.moduleLoader.getChunkFileName.bind(this.graph.moduleLoader),
getExports: this.getExports.bind(this),
getModuleExecIndex: () => this.execIndex,
getModuleName: this.basename.bind(this),
getReexports: this.getReexports.bind(this),
importDescriptions: this.importDescriptions,
includeDynamicImport: this.includeDynamicImport.bind(this),
includeVariable: this.includeVariable.bind(this),
isCrossChunkImport: importDescription =>
(importDescription.module as Module).chunk !== this.chunk,
magicString: this.magicString,
module: this,
moduleContext: this.context,
nodeConstructors,
preserveModules: this.graph.preserveModules,
propertyReadSideEffects: (!this.graph.treeshakingOptions ||
this.graph.treeshakingOptions.propertyReadSideEffects) as boolean,
traceExport: this.getVariableForExportName.bind(this),
traceVariable: this.traceVariable.bind(this),
treeshake: !!this.graph.treeshakingOptions,
tryCatchDeoptimization: (!this.graph.treeshakingOptions ||
this.graph.treeshakingOptions.tryCatchDeoptimization) as boolean,
usesTopLevelAwait: false,
warn: this.warn.bind(this)
};
this.scope = new ModuleScope(this.graph.scope, this.astContext);
this.ast = new Program(
this.esTreeAst,
{ type: 'Module', context: this.astContext },
this.scope
);
timeEnd('analyse ast', 3);
}
toJSON(): ModuleJSON {
return {
ast: this.esTreeAst,
code: this.code,
customTransformCache: this.customTransformCache,
dependencies: this.dependencies.map(module => module.id),
id: this.id,
moduleSideEffects: this.moduleSideEffects,
originalCode: this.originalCode,
originalSourcemap: this.originalSourcemap,
resolvedIds: this.resolvedIds,
sourcemapChain: this.sourcemapChain,
transformAssets: this.transformAssets,
transformChunks: this.transformChunks,
transformDependencies: this.transformDependencies
};
}
traceVariable(name: string): Variable | null {
const localVariable = this.scope.variables.get(name);
if (localVariable) {
return localVariable;
}
if (name in this.importDescriptions) {
const importDeclaration = this.importDescriptions[name];
const otherModule = importDeclaration.module as Module | ExternalModule;
if (otherModule instanceof Module && importDeclaration.name === '*') {
return otherModule.getOrCreateNamespace();
}
const declaration = otherModule.getVariableForExportName(importDeclaration.name);
if (!declaration) {
handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
}
return declaration;
}
return null;
}
warn(warning: RollupWarning, pos: number) {
if (pos !== undefined) {
warning.pos = pos;
const { line, column } = locate(this.code, pos, { offsetLine: 1 }); // TODO trace sourcemaps, cf. error()
warning.loc = { file: this.id, line, column };
warning.frame = getCodeFrame(this.code, line, column);
}
warning.id = this.id;
this.graph.warn(warning);
}
private addDynamicImport(node: Import) {
this.dynamicImports.push({ node, resolution: null });
}
private addExport(
node: ExportAllDeclaration | ExportNamedDeclaration | ExportDefaultDeclaration
) {
const source =
(node as ExportAllDeclaration).source && (node as ExportAllDeclaration).source.value;
// export { name } from './other'
if (source) {
if (this.sources.indexOf(source) === -1) this.sources.push(source);
if (node.type === NodeType.ExportAllDeclaration) {
// Store `export * from '...'` statements in an array of delegates.
// When an unknown import is encountered, we see if one of them can satisfy it.
this.exportAllSources.push(source);
} else {
for (const specifier of (node as ExportNamedDeclaration).specifiers) {
const name = specifier.exported.name;
if (this.exports[name] || this.reexports[name]) {
this.error(
{
code: 'DUPLICATE_EXPORT',
message: `A module cannot have multiple exports with the same name ('${name}')`
},
specifier.start
);
}
this.reexports[name] = {
localName: specifier.local.name,
module: null as any, // filled in later,
source,
start: specifier.start
};
}
}
} else if (node instanceof ExportDefaultDeclaration) {
// export default function foo () {}
// export default foo;
// export default 42;
if (this.exports.default) {
this.error(
{
code: 'DUPLICATE_EXPORT',
message: `A module can only have one default export`
},
node.start
);
}
this.exports.default = {
identifier: node.variable.getAssignedVariableName(),
localName: 'default'
};
} else if ((node as ExportNamedDeclaration).declaration) {
// export var { foo, bar } = ...
// export var foo = 42;
// export var a = 1, b = 2, c = 3;
// export function foo () {}
const declaration = (node as ExportNamedDeclaration).declaration as
| FunctionDeclaration
| ClassDeclaration
| VariableDeclaration;
if (declaration.type === NodeType.VariableDeclaration) {
for (const decl of declaration.declarations) {
for (const localName of extractAssignedNames(decl.id)) {
this.exports[localName] = { identifier: null, localName };
}
}
} else {
// export function foo () {}
const localName = (declaration.id as Identifier).name;
this.exports[localName] = { identifier: null, localName };
}
} else {
// export { foo, bar, baz }
for (const specifier of (node as ExportNamedDeclaration).specifiers) {
const localName = specifier.local.name;
const exportedName = specifier.exported.name;
if (this.exports[exportedName] || this.reexports[exportedName]) {
this.error(
{
code: 'DUPLICATE_EXPORT',
message: `A module cannot have multiple exports with the same name ('${exportedName}')`
},
specifier.start
);
}
this.exports[exportedName] = { identifier: null, localName };
}
}
}
private addImport(node: ImportDeclaration) {
const source = node.source.value;
if (this.sources.indexOf(source) === -1) this.sources.push(source);
for (const specifier of node.specifiers) {
const localName = specifier.local.name;
if (this.importDescriptions[localName]) {
this.error(
{
code: 'DUPLICATE_IMPORT',
message: `Duplicated import '${localName}'`
},
specifier.start
);
}
const isDefault = specifier.type === NodeType.ImportDefaultSpecifier;
const isNamespace = specifier.type === NodeType.ImportNamespaceSpecifier;
const name = isDefault
? 'default'
: isNamespace
? '*'
: (specifier as ImportSpecifier).imported.name;
this.importDescriptions[localName] = { source, start: specifier.start, name, module: null };
}
}
private addImportMeta(node: MetaProperty) {
this.importMetas.push(node);
}
private addModulesToSpecifiers(specifiers: {
[name: string]: ImportDescription | ReexportDescription;
}) {
for (const name of Object.keys(specifiers)) {
const specifier = specifiers[name];
const id = this.resolvedIds[specifier.source].id;
specifier.module = this.graph.moduleById.get(id) as Module | ExternalModule | null;
}
}
private includeDynamicImport(node: Import) {
const resolution = (this.dynamicImports.find(dynamicImport => dynamicImport.node === node) as {
resolution: string | Module | ExternalModule | undefined;
}).resolution;
if (resolution instanceof Module) {
resolution.dynamicallyImportedBy.push(this);
resolution.includeAllExports();
}
}
private includeVariable(variable: Variable) {
const variableModule = variable.module;
if (!variable.included) {
variable.include();
this.graph.needsTreeshakingPass = true;
}
if (variableModule && variableModule !== this) {
this.imports.add(variable);
}
}
private removeExistingSourceMap() {
for (const comment of this.comments) {
if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
this.magicString.remove(comment.start, comment.end);
}
}
}
private shimMissingExport(name: string): void {
if (!this.exports[name]) {
this.graph.warn({
code: 'SHIMMED_EXPORT',
exporter: relativeId(this.id),
exportName: name,
message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
});
this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
}
}
}