UNPKG

1.56 kBJavaScriptView Raw
1import { blank } from './utils/object.js';
2import makeLegalIdentifier from './utils/makeLegalIdentifier.js';
3
4class ExternalDeclaration {
5 constructor ( module, name ) {
6 this.module = module;
7 this.name = name;
8 this.isExternal = true;
9 }
10
11 addAlias () {
12 // noop
13 }
14
15 addReference ( reference ) {
16 reference.declaration = this;
17
18 if ( this.name === 'default' || this.name === '*' ) {
19 this.module.suggestName( reference.name );
20 }
21 }
22
23 render ( es6 ) {
24 if ( this.name === '*' ) {
25 return this.module.name;
26 }
27
28 if ( this.name === 'default' ) {
29 return !es6 && this.module.exportsNames ?
30 `${this.module.name}__default` :
31 this.module.name;
32 }
33
34 return es6 ? this.name : `${this.module.name}.${this.name}`;
35 }
36
37 use () {
38 // noop?
39 }
40}
41
42export default class ExternalModule {
43 constructor ( id ) {
44 this.id = id;
45 this.name = makeLegalIdentifier( id );
46
47 this.nameSuggestions = blank();
48 this.mostCommonSuggestion = 0;
49
50 this.isExternal = true;
51 this.declarations = blank();
52
53 this.exportsNames = false;
54 }
55
56 suggestName ( name ) {
57 if ( !this.nameSuggestions[ name ] ) this.nameSuggestions[ name ] = 0;
58 this.nameSuggestions[ name ] += 1;
59
60 if ( this.nameSuggestions[ name ] > this.mostCommonSuggestion ) {
61 this.mostCommonSuggestion = this.nameSuggestions[ name ];
62 this.name = name;
63 }
64 }
65
66 traceExport ( name ) {
67 if ( name !== 'default' && name !== '*' ) {
68 this.exportsNames = true;
69 }
70
71 return this.declarations[ name ] || (
72 this.declarations[ name ] = new ExternalDeclaration( this, name )
73 );
74 }
75}