UNPKG

1.78 kBJavaScriptView Raw
1"use strict";
2
3const Path = require('path');
4
5const types = require('@babel/types');
6
7const VARS = {
8 process: asset => {
9 asset.addDependency('process');
10 return 'var process = require("process");';
11 },
12 global: asset => `var global = arguments[${asset.options.scopeHoist ? 0 : 3}];`,
13 __dirname: asset => `var __dirname = ${JSON.stringify(Path.dirname(asset.name))};`,
14 __filename: asset => `var __filename = ${JSON.stringify(asset.name)};`,
15 Buffer: asset => {
16 asset.addDependency('buffer');
17 return 'var Buffer = require("buffer").Buffer;';
18 },
19 // Prevent AMD defines from working when loading UMD bundles.
20 // Ideally the CommonJS check would come before the AMD check, but many
21 // existing modules do the checks the opposite way leading to modules
22 // not exporting anything to Parcel.
23 define: () => 'var define;'
24};
25module.exports = {
26 Identifier(node, asset, ancestors) {
27 let parent = ancestors[ancestors.length - 2];
28
29 if (VARS.hasOwnProperty(node.name) && !asset.globals.has(node.name) && types.isReferenced(node, parent)) {
30 asset.globals.set(node.name, VARS[node.name](asset));
31 }
32 },
33
34 Declaration(node, asset, ancestors) {
35 // If there is a global declaration of one of the variables, remove our declaration
36 let identifiers = types.getBindingIdentifiers(node);
37
38 for (let id in identifiers) {
39 if (VARS.hasOwnProperty(id) && !inScope(ancestors)) {
40 // Don't delete entirely, so we don't add it again when the declaration is referenced
41 asset.globals.set(id, '');
42 }
43 }
44 }
45
46};
47
48function inScope(ancestors) {
49 for (let i = ancestors.length - 2; i >= 0; i--) {
50 if (types.isScope(ancestors[i]) && !types.isProgram(ancestors[i])) {
51 return true;
52 }
53 }
54
55 return false;
56}
\No newline at end of file