This repository has been archived by the owner on Aug 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 126
/
index.js
266 lines (221 loc) · 7.66 KB
/
index.js
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
import { existsSync, readFileSync } from 'fs';
import { extname, resolve, join } from 'path';
import { sync as nodeResolveSync } from 'resolve';
import { createFilter } from 'rollup-pluginutils';
import { getDynamicRequirePaths } from './dynamic-require-paths';
import {
DYNAMIC_JSON_PREFIX,
DYNAMIC_PACKAGES_ID,
DYNAMIC_REGISTER_PREFIX,
EXTERNAL_PREFIX,
HELPERS,
HELPERS_ID,
PROXY_PREFIX
} from './helpers.js';
import {getIsCjsPromise, setIsCjsPromise} from './is-cjs';
import {getResolveId} from './resolve-id';
import {
checkEsModule,
normalizePathSlashes,
hasCjsKeywords,
transformCommonjs
} from './transform.js';
import { getName } from './utils.js';
export default function commonjs(options = {}) {
const extensions = options.extensions || ['.js'];
const filter = createFilter(options.include, options.exclude);
const ignoreGlobal = options.ignoreGlobal;
const { dynamicRequireModuleSet, dynamicRequireModuleDirPaths } = getDynamicRequirePaths(
options.dynamicRequireTargets
);
const isDynamicRequireModulesEnabled = dynamicRequireModuleSet.size > 0;
const customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach(id => {
let resolvedId;
try {
resolvedId = nodeResolveSync(id, { basedir: process.cwd() });
} catch (err) {
resolvedId = resolve(id);
}
customNamedExports[resolvedId] = options.namedExports[id];
});
}
const esModulesWithoutDefaultExport = Object.create(null);
const esModulesWithDefaultExport = Object.create(null);
const ignoreRequire =
typeof options.ignore === 'function'
? options.ignore
: Array.isArray(options.ignore)
? id => options.ignore.includes(id)
: () => false;
let entryModuleIdsPromise = null;
const resolveId = getResolveId(extensions);
const sourceMap = options.sourceMap !== false;
let mainModuleId = null;
return {
name: 'commonjs',
options(options) {
resolveId.setRollupOptions(options);
const input = options.input || options.entry;
const entryModules = Array.isArray(input)
? input
: typeof input === 'object' && input !== null
? Object.values(input)
: [input];
entryModuleIdsPromise = Promise.all(entryModules.map(entry => resolveId(entry)));
},
resolveId,
load(id) {
if (id === HELPERS_ID) return HELPERS;
// generate proxy modules
if (id.startsWith(EXTERNAL_PREFIX)) {
const actualId = id.slice(EXTERNAL_PREFIX.length);
const name = getName(actualId);
if (actualId === HELPERS_ID || actualId === DYNAMIC_PACKAGES_ID)
// These do not export default
return `import * as ${name} from ${JSON.stringify(actualId)}; export default ${name};`;
return `import ${name} from ${JSON.stringify(actualId)}; export default ${name};`;
}
if (id === DYNAMIC_PACKAGES_ID) {
let code = `const { commonjsRegister } = require('${HELPERS_ID}');`;
for (const dir of dynamicRequireModuleDirPaths) {
let entryPoint = 'index.js';
try {
if (existsSync(join(dir, 'package.json'))) {
entryPoint = JSON.parse(
readFileSync(join(dir, 'package.json'), { encoding: 'utf8' })
).main || entryPoint;
}
} catch (ignored) {
// ignored
}
code += `\ncommonjsRegister(${JSON.stringify(
dir
)}, function (module, exports) {
module.exports = require(${JSON.stringify(
normalizePathSlashes(join(dir, entryPoint))
)});
});`;
}
return code;
}
const isDynamicJson = id.startsWith(DYNAMIC_JSON_PREFIX);
if (isDynamicJson) {
id = id.slice(DYNAMIC_JSON_PREFIX.length);
}
const normalizedPath = normalizePathSlashes(id);
if (isDynamicJson) {
return `require('${HELPERS_ID}').commonjsRegister(${JSON.stringify(
normalizedPath
)}, function (module, exports) {
module.exports = require(${JSON.stringify(normalizedPath)});
});`;
}
if (dynamicRequireModuleSet.has(normalizedPath)) {
// Try our best to still export the module fully.
// The commonjs polyfill should take care of circular references.
return `require('${HELPERS_ID}').commonjsRegister(${JSON.stringify(
normalizedPath
)}, function (module, exports) {
${readFileSync(normalizedPath, { encoding: 'utf8' })}
});`;
}
if (id.startsWith(PROXY_PREFIX)) {
const actualId = id.slice(PROXY_PREFIX.length);
const name = getName(actualId);
return getIsCjsPromise(actualId).then(isCjs => {
if (dynamicRequireModuleSet.has(normalizePathSlashes(actualId)))
return `import {commonjsRequire} from '${HELPERS_ID}'; const ${name} = commonjsRequire(${JSON.stringify(
normalizePathSlashes(actualId)
)}); export default (${name} && ${name}['default']) || ${name}`;
else if (isCjs)
return `import { __moduleExports } from ${JSON.stringify(
actualId
)}; export default __moduleExports;`;
else if (esModulesWithoutDefaultExport[actualId])
return `import * as ${name} from ${JSON.stringify(actualId)}; export default ${name};`;
else if (esModulesWithDefaultExport[actualId]) {
return `export {default} from ${JSON.stringify(actualId)};`;
} else
return `import * as ${name} from ${JSON.stringify(
actualId
)}; import {getCjsExportFromNamespace} from "${HELPERS_ID}"; export default getCjsExportFromNamespace(${name})`;
});
}
// TODO: For code splitting, the runtime probably needs to be imported by each entry point
// TODO: This does not work and will leave untranspiled requires if the entry point is an ES Module
if (!mainModuleId && isDynamicRequireModulesEnabled) {
mainModuleId = id;
let code;
try {
code = readFileSync(id, {encoding: 'utf8'});
} catch (ex) {
this.warn(`Failed to read file ${id}, dynamic modules might not work correctly`);
return;
}
let dynamicImports = Array.from(dynamicRequireModuleSet)
.map(id => `require(${JSON.stringify(DYNAMIC_REGISTER_PREFIX + id)});`)
.join('\n');
if (dynamicRequireModuleDirPaths.length) {
dynamicImports += `require(${JSON.stringify(
DYNAMIC_REGISTER_PREFIX + DYNAMIC_PACKAGES_ID
)});`;
}
code = dynamicImports + '\n' + code;
return code;
}
},
transform(code, id) {
if (id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
if (!filter(id) || extensions.indexOf(extname(id)) === -1) {
setIsCjsPromise(id, Promise.resolve(null));
return null;
}
}
const transformPromise = entryModuleIdsPromise
.then(entryModuleIds => {
const { isEsModule, hasDefaultExport, ast } = checkEsModule(this.parse, code, id);
const isDynamicRequireModule = dynamicRequireModuleSet.has(
normalizePathSlashes(id)
);
let avoidAddingDefaultExport = false;
if (isEsModule && !isDynamicRequireModule) {
(hasDefaultExport ? esModulesWithDefaultExport : esModulesWithoutDefaultExport)[
id
] = true;
avoidAddingDefaultExport = true;
}
// it is not an ES module but it does not have CJS-specific elements.
else if (!hasCjsKeywords(code, ignoreGlobal)) {
esModulesWithoutDefaultExport[id] = true;
return null;
}
const transformed = transformCommonjs(
this.parse,
code,
id,
entryModuleIds.indexOf(id) !== -1,
ignoreGlobal,
ignoreRequire,
customNamedExports[id],
sourceMap,
dynamicRequireModuleSet,
ast,
avoidAddingDefaultExport
);
if (!transformed) {
if (!isEsModule || isDynamicRequireModule)
esModulesWithoutDefaultExport[id] = true;
return null;
}
return transformed;
})
.catch(err => {
this.error(err, err.loc);
});
setIsCjsPromise(id, transformPromise.then(Boolean, () => false));
return transformPromise;
}
};
}