@parcel/packager-js 2.0.0-dev.1712 → 2.0.0-dev.1789

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -40,7 +40,7 @@ function _fs() {
40
40
  return data;
41
41
  }
42
42
  var _utils2 = require("./utils");
43
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
43
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
44
44
  const PRELUDE = _fs().default.readFileSync(_path().default.join(__dirname, 'dev-prelude.js'), 'utf8').trim().replace(/;$/, '');
45
45
  class DevPackager {
46
46
  constructor(options, bundleGraph, bundle, parcelRequireName) {
@@ -71,6 +71,7 @@ class DevPackager {
71
71
  let prefix = this.getPrefix();
72
72
  let lineOffset = (0, _utils().countLines)(prefix);
73
73
  let script = null;
74
+ let usedHelpers = 0;
74
75
  this.bundle.traverse(node => {
75
76
  let wrapped = first ? '' : ',';
76
77
  if (node.type === 'dependency') {
@@ -87,6 +88,9 @@ class DevPackager {
87
88
  if (node.type === 'asset') {
88
89
  let asset = node.value;
89
90
  (0, _assert().default)(asset.type === 'js', 'all assets in a js bundle must be js assets');
91
+ if (typeof asset.meta.usedHelpers === 'number') {
92
+ usedHelpers |= asset.meta.usedHelpers;
93
+ }
90
94
 
91
95
  // If this is the main entry of a script rather than a module, we need to hoist it
92
96
  // outside the bundle wrapper function so that its variables are exposed as globals.
@@ -98,13 +102,24 @@ class DevPackager {
98
102
  let dependencies = this.bundleGraph.getDependencies(asset);
99
103
  for (let dep of dependencies) {
100
104
  let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
105
+ let specifier = (0, _utils2.getSpecifier)(dep);
101
106
  if (this.bundleGraph.isDependencySkipped(dep)) {
102
- deps[(0, _utils2.getSpecifier)(dep)] = false;
107
+ deps[specifier] = false;
103
108
  } else if (resolved) {
104
- deps[(0, _utils2.getSpecifier)(dep)] = this.bundleGraph.getAssetPublicId(resolved);
109
+ deps[specifier] = this.bundleGraph.getAssetPublicId(resolved);
105
110
  } else {
106
111
  // An external module - map placeholder to original specifier.
107
- deps[(0, _utils2.getSpecifier)(dep)] = dep.specifier;
112
+ deps[specifier] = dep.specifier;
113
+ }
114
+ }
115
+
116
+ // Add dependencies for parcelRequire calls added by runtimes
117
+ // so that the HMR runtime can correctly traverse parents.
118
+ let hmrDeps = asset.meta.hmrDeps;
119
+ if (this.options.hmrOptions && Array.isArray(hmrDeps)) {
120
+ for (let id of hmrDeps) {
121
+ (0, _assert().default)(typeof id === 'string');
122
+ deps[id] = id;
108
123
  }
109
124
  }
110
125
  let {
@@ -135,7 +150,7 @@ class DevPackager {
135
150
  });
136
151
  let entries = this.bundle.getEntryAssets();
137
152
  let mainEntry = this.bundle.getMainEntry();
138
- if (!this.isEntry() && this.bundle.env.outputFormat === 'global' || this.bundle.env.sourceType === 'script') {
153
+ if (!this.isEntry() && this.bundle.env.outputFormat !== 'commonjs' || this.bundle.env.sourceType === 'script') {
139
154
  // In async bundles we don't want the main entry to execute until we require it
140
155
  // as there might be dependencies in a sibling bundle that hasn't loaded yet.
141
156
  entries = entries.filter(a => {
@@ -144,7 +159,24 @@ class DevPackager {
144
159
  });
145
160
  mainEntry = null;
146
161
  }
147
- let contents = prefix + '({' + assets + '},' + JSON.stringify(entries.map(asset => this.bundleGraph.getAssetPublicId(asset))) + ', ' + JSON.stringify(mainEntry ? this.bundleGraph.getAssetPublicId(mainEntry) : null) + ', ' + JSON.stringify(this.parcelRequireName) + ')' + '\n';
162
+ if (usedHelpers & 4) {
163
+ prefix = prefix.replace('// INSERT_LOAD_HERE', 'newRequire.load = function (url) { return import(distDir + "/" + url); }');
164
+ }
165
+ let contents = prefix + '({' + assets + '},' + JSON.stringify(entries.map(asset => this.bundleGraph.getAssetPublicId(asset))) + ', ' + JSON.stringify(mainEntry ? this.bundleGraph.getAssetPublicId(mainEntry) : null) + ', ' + JSON.stringify(this.parcelRequireName);
166
+ if (usedHelpers & 1) {
167
+ // Generate a relative path from this bundle to the root of the dist dir.
168
+ let distDir = (0, _utils().relativePath)(_path().default.dirname(this.bundle.name), '');
169
+ if (distDir.endsWith('/')) {
170
+ distDir = distDir.slice(0, -1);
171
+ }
172
+ contents += ', ' + JSON.stringify(distDir);
173
+ } else if (usedHelpers & 2) {
174
+ contents += ', null';
175
+ }
176
+ if (usedHelpers & 2) {
177
+ contents += ', ' + JSON.stringify(this.bundle.target.publicUrl);
178
+ }
179
+ contents += ')\n';
148
180
 
149
181
  // The entry asset of a script bundle gets hoisted outside the bundle wrapper function
150
182
  // so that its variables become globals. We need to replace any require calls for
@@ -179,6 +211,14 @@ class DevPackager {
179
211
  for (let b of bundles) {
180
212
  importScripts += `importScripts("${(0, _utils().relativeBundlePath)(this.bundle, b)}");\n`;
181
213
  }
214
+ } else if (this.bundle.env.isNode()) {
215
+ let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
216
+ for (let b of bundles) {
217
+ if (b.type !== 'js') {
218
+ continue;
219
+ }
220
+ importScripts += `require("${(0, _utils().relativeBundlePath)(this.bundle, b)}");\n`;
221
+ }
182
222
  }
183
223
  return (
184
224
  // If the entry asset included a hashbang, repeat it at the top of the bundle
@@ -59,20 +59,24 @@ var _GlobalOutputFormat = require("./GlobalOutputFormat");
59
59
  var _helpers = require("./helpers");
60
60
  var _utils2 = require("./utils");
61
61
  function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
62
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
63
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
62
+ function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
63
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
64
64
  // General regex used to replace imports with the resolved code, references with resolutions,
65
65
  // and count the number of newlines in the file for source maps.
66
66
  const REPLACEMENT_RE = /\n|import\s+"([0-9a-f]{16}:.+?)";|(?:\$[0-9a-f]{16}\$exports)|(?:\$[0-9a-f]{16}\$(?:import|importAsync|require)\$[0-9a-f]+(?:\$[0-9a-f]+)?)/g;
67
67
  const BUILTINS = Object.keys(_globals().default.builtin);
68
+ const BROWSER_BUILTINS = new Set([...BUILTINS, ...Object.keys(_globals().default.browser)]);
69
+ const NODE_BUILTINS = new Set([...BUILTINS, ...Object.keys(_globals().default.node)]);
68
70
  const GLOBALS_BY_CONTEXT = {
69
- browser: new Set([...BUILTINS, ...Object.keys(_globals().default.browser)]),
71
+ browser: BROWSER_BUILTINS,
72
+ 'react-client': BROWSER_BUILTINS,
70
73
  'web-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.worker)]),
71
74
  'service-worker': new Set([...BUILTINS, ...Object.keys(_globals().default.serviceworker)]),
72
75
  worklet: new Set([...BUILTINS]),
73
- node: new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
74
- 'electron-main': new Set([...BUILTINS, ...Object.keys(_globals().default.node)]),
75
- 'electron-renderer': new Set([...BUILTINS, ...Object.keys(_globals().default.node), ...Object.keys(_globals().default.browser)])
76
+ node: NODE_BUILTINS,
77
+ 'electron-main': NODE_BUILTINS,
78
+ 'electron-renderer': new Set([...BUILTINS, ...Object.keys(_globals().default.node), ...Object.keys(_globals().default.browser)]),
79
+ 'react-server': NODE_BUILTINS
76
80
  };
77
81
  const OUTPUT_FORMATS = {
78
82
  esmodule: _ESMOutputFormat.ESMOutputFormat,
@@ -110,11 +114,13 @@ class ScopeHoistingPackager {
110
114
  // runtimes are excluded, and instead we add imports into the entry bundle
111
115
  // of each bundle group pointing at the sibling bundles. These can be
112
116
  // picked up by another bundler later at which point runtimes will be added.
113
- if (this.bundle.env.isLibrary || this.bundle.env.outputFormat === 'commonjs') {
117
+ if (this.bundle.env.isLibrary || this.bundle.env.outputFormat === 'commonjs' || this.bundle.env.outputFormat === 'esmodule' && !this.isAsyncBundle) {
114
118
  for (let b of this.bundleGraph.getReferencedBundles(this.bundle, {
115
119
  recursive: false
116
120
  })) {
117
- this.externals.set((0, _utils().relativeBundlePath)(this.bundle, b), new Map());
121
+ if (this.bundle.env.isLibrary || b.type === 'js') {
122
+ this.externals.set((0, _utils().relativeBundlePath)(this.bundle, b), new Map());
123
+ }
118
124
  }
119
125
  }
120
126
  let res = '';
@@ -286,7 +292,7 @@ class ScopeHoistingPackager {
286
292
  // If the module has a namespace (e.g. commonjs), and this is not an entry, only export the namespace
287
293
  // as default, without individual exports. This mirrors the importing logic in addExternal, avoiding
288
294
  // extra unused exports and potential for non-identifier export names.
289
- if (hasNamespace && this.isAsyncBundle && exportAs !== '*') {
295
+ if (hasNamespace && !this.bundle.needsStableName && exportAs !== '*') {
290
296
  continue;
291
297
  }
292
298
  let symbols = (_this$exportedSymbols = this.exportedSymbols.get(symbol === '*' ? (0, _nullthrows().default)((_entry$symbols$get2 = entry.symbols.get('*')) === null || _entry$symbols$get2 === void 0 ? void 0 : _entry$symbols$get2.local) : symbol)) === null || _this$exportedSymbols === void 0 ? void 0 : _this$exportedSymbols.exportAs;
@@ -387,6 +393,18 @@ class ScopeHoistingPackager {
387
393
  if (code.includes('$parcel$global')) {
388
394
  this.usedHelpers.add('$parcel$global');
389
395
  }
396
+ let usedHelpers = asset.meta.usedHelpers;
397
+ if (typeof usedHelpers === 'number') {
398
+ if (usedHelpers & 1) {
399
+ this.usedHelpers.add('$parcel$distDir');
400
+ }
401
+ if (usedHelpers & 2) {
402
+ this.usedHelpers.add('$parcel$publicUrl');
403
+ }
404
+ if (usedHelpers & 4) {
405
+ this.usedHelpers.add('$parcel$import');
406
+ }
407
+ }
390
408
  if (this.bundle.env.isNode() && asset.meta.has_node_replacements) {
391
409
  const relPath = (0, _utils().normalizeSeparators)(_path().default.relative(this.bundle.target.distDir, _path().default.dirname(asset.filePath)));
392
410
  code = code.replace('$parcel$dirnameReplace', relPath);
@@ -982,7 +1000,7 @@ ${code}
982
1000
  for (let helper of this.usedHelpers) {
983
1001
  let currentHelper = _helpers.helpers[helper];
984
1002
  if (typeof currentHelper === 'function') {
985
- currentHelper = _helpers.helpers[helper](this.bundle.env);
1003
+ currentHelper = _helpers.helpers[helper](this.bundle.env, this.bundle);
986
1004
  }
987
1005
  res += currentHelper;
988
1006
  if (enableSourceMaps) {
@@ -6,7 +6,7 @@
6
6
  // anything defined in a previous bundle is accessed via the
7
7
  // orig method which is the require for previous bundles
8
8
 
9
- (function (modules, entry, mainEntry, parcelRequireName, globalName) {
9
+ (function (modules, entry, mainEntry, parcelRequireName, distDir, publicUrl) {
10
10
  /* eslint-disable no-undef */
11
11
  var globalObject =
12
12
  typeof globalThis !== 'undefined'
@@ -101,6 +101,8 @@
101
101
  newRequire.modules = modules;
102
102
  newRequire.cache = cache;
103
103
  newRequire.parent = previousRequire;
104
+ newRequire.distDir = distDir;
105
+ newRequire.publicUrl = publicUrl;
104
106
  newRequire.register = function (id, exports) {
105
107
  modules[id] = [
106
108
  function (require, module) {
@@ -110,6 +112,10 @@
110
112
  ];
111
113
  };
112
114
 
115
+ // Only insert newRequire.load when it is actually used.
116
+ // The code in this file is linted against ES5, so dynamic import is not allowed.
117
+ // INSERT_LOAD_HERE
118
+
113
119
  Object.defineProperty(newRequire, 'root', {
114
120
  get: function () {
115
121
  return globalObject[parcelRequireName];
@@ -136,10 +142,6 @@
136
142
  define(function () {
137
143
  return mainExports;
138
144
  });
139
-
140
- // <script>
141
- } else if (globalName) {
142
- this[globalName] = mainExports;
143
145
  }
144
146
  }
145
147
  });
package/lib/helpers.js CHANGED
@@ -4,6 +4,21 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.prelude = exports.helpers = exports.fnExpr = exports.bundleQueuePrelude = void 0;
7
+ function _utils() {
8
+ const data = require("@parcel/utils");
9
+ _utils = function () {
10
+ return data;
11
+ };
12
+ return data;
13
+ }
14
+ function _path() {
15
+ const data = _interopRequireDefault(require("path"));
16
+ _path = function () {
17
+ return data;
18
+ };
19
+ return data;
20
+ }
21
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
7
22
  const prelude = parcelRequireName => `
8
23
  var $parcel$modules = {};
9
24
  var $parcel$inits = {};
@@ -120,10 +135,27 @@ function $parcel$defineInteropFlag(a) {
120
135
  Object.defineProperty(a, '__esModule', {value: true, configurable: true});
121
136
  }
122
137
  `;
138
+ const $parcel$distDir = (env, bundle) => {
139
+ // Generate a relative path from this bundle to the root of the dist dir.
140
+ let distDir = (0, _utils().relativePath)(_path().default.dirname(bundle.name), '');
141
+ if (distDir.endsWith('/')) {
142
+ distDir = distDir.slice(0, -1);
143
+ }
144
+ return `var $parcel$distDir = ${JSON.stringify(distDir)};\n`;
145
+ };
146
+ const $parcel$publicUrl = (env, bundle) => {
147
+ return `var $parcel$publicUrl = ${JSON.stringify(bundle.target.publicUrl)};\n`;
148
+ };
149
+ const $parcel$import = env => {
150
+ return `var $parcel$import = ${fnExpr(env, ['url'], ['return import($parcel$distDir + "/" + url);'])};\n`;
151
+ };
123
152
  const helpers = exports.helpers = {
124
153
  $parcel$export,
125
154
  $parcel$exportWildcard,
126
155
  $parcel$interopDefault,
127
156
  $parcel$global,
128
- $parcel$defineInteropFlag
157
+ $parcel$defineInteropFlag,
158
+ $parcel$distDir,
159
+ $parcel$publicUrl,
160
+ $parcel$import
129
161
  };
package/lib/index.js CHANGED
@@ -41,7 +41,7 @@ function _nullthrows() {
41
41
  }
42
42
  var _DevPackager = require("./DevPackager");
43
43
  var _ScopeHoistingPackager = require("./ScopeHoistingPackager");
44
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
44
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
45
45
  const CONFIG_SCHEMA = {
46
46
  type: 'object',
47
47
  properties: {
package/lib/utils.js CHANGED
@@ -14,7 +14,7 @@ function _nullthrows() {
14
14
  };
15
15
  return data;
16
16
  }
17
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
18
18
  // This replaces __parcel__require__ references left by the transformer with
19
19
  // parcelRequire calls of the resolved asset id. This lets runtimes work within
20
20
  // script bundles, which must be outside the bundle wrapper so their variables are global.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcel/packager-js",
3
- "version": "2.0.0-dev.1712+c6bc8e411",
3
+ "version": "2.0.0-dev.1789+0b82b13d6",
4
4
  "license": "MIT",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -17,17 +17,17 @@
17
17
  "source": "src/index.js",
18
18
  "engines": {
19
19
  "node": ">= 16.0.0",
20
- "parcel": "^2.0.0-dev.1710+c6bc8e411"
20
+ "parcel": "^2.0.0-dev.1787+0b82b13d6"
21
21
  },
22
22
  "dependencies": {
23
- "@parcel/diagnostic": "2.0.0-dev.1712+c6bc8e411",
24
- "@parcel/plugin": "2.0.0-dev.1712+c6bc8e411",
25
- "@parcel/rust": "2.12.1-dev.3335+c6bc8e411",
23
+ "@parcel/diagnostic": "2.0.0-dev.1789+0b82b13d6",
24
+ "@parcel/plugin": "2.0.0-dev.1789+0b82b13d6",
25
+ "@parcel/rust": "2.13.3-dev.3412+0b82b13d6",
26
26
  "@parcel/source-map": "^2.1.1",
27
- "@parcel/types": "2.0.0-dev.1712+c6bc8e411",
28
- "@parcel/utils": "2.0.0-dev.1712+c6bc8e411",
27
+ "@parcel/types": "2.0.0-dev.1789+0b82b13d6",
28
+ "@parcel/utils": "2.0.0-dev.1789+0b82b13d6",
29
29
  "globals": "^13.2.0",
30
30
  "nullthrows": "^1.1.1"
31
31
  },
32
- "gitHead": "c6bc8e41105247c437089ec3cb91e53f12ac5519"
32
+ "gitHead": "0b82b13d6c0dae58ae636983bbd57dbcf94fff89"
33
33
  }
@@ -6,6 +6,7 @@ import {
6
6
  relativeBundlePath,
7
7
  countLines,
8
8
  normalizeSeparators,
9
+ relativePath,
9
10
  } from '@parcel/utils';
10
11
  import SourceMap from '@parcel/source-map';
11
12
  import invariant from 'assert';
@@ -60,6 +61,7 @@ export class DevPackager {
60
61
  let lineOffset = countLines(prefix);
61
62
  let script: ?{|code: string, mapBuffer: ?Buffer|} = null;
62
63
 
64
+ let usedHelpers = 0;
63
65
  this.bundle.traverse(node => {
64
66
  let wrapped = first ? '' : ',';
65
67
 
@@ -87,6 +89,10 @@ export class DevPackager {
87
89
  'all assets in a js bundle must be js assets',
88
90
  );
89
91
 
92
+ if (typeof asset.meta.usedHelpers === 'number') {
93
+ usedHelpers |= asset.meta.usedHelpers;
94
+ }
95
+
90
96
  // If this is the main entry of a script rather than a module, we need to hoist it
91
97
  // outside the bundle wrapper function so that its variables are exposed as globals.
92
98
  if (
@@ -101,14 +107,24 @@ export class DevPackager {
101
107
  let dependencies = this.bundleGraph.getDependencies(asset);
102
108
  for (let dep of dependencies) {
103
109
  let resolved = this.bundleGraph.getResolvedAsset(dep, this.bundle);
110
+ let specifier = getSpecifier(dep);
104
111
  if (this.bundleGraph.isDependencySkipped(dep)) {
105
- deps[getSpecifier(dep)] = false;
112
+ deps[specifier] = false;
106
113
  } else if (resolved) {
107
- deps[getSpecifier(dep)] =
108
- this.bundleGraph.getAssetPublicId(resolved);
114
+ deps[specifier] = this.bundleGraph.getAssetPublicId(resolved);
109
115
  } else {
110
116
  // An external module - map placeholder to original specifier.
111
- deps[getSpecifier(dep)] = dep.specifier;
117
+ deps[specifier] = dep.specifier;
118
+ }
119
+ }
120
+
121
+ // Add dependencies for parcelRequire calls added by runtimes
122
+ // so that the HMR runtime can correctly traverse parents.
123
+ let hmrDeps = asset.meta.hmrDeps;
124
+ if (this.options.hmrOptions && Array.isArray(hmrDeps)) {
125
+ for (let id of hmrDeps) {
126
+ invariant(typeof id === 'string');
127
+ deps[id] = id;
112
128
  }
113
129
  }
114
130
 
@@ -161,7 +177,7 @@ export class DevPackager {
161
177
  let entries = this.bundle.getEntryAssets();
162
178
  let mainEntry = this.bundle.getMainEntry();
163
179
  if (
164
- (!this.isEntry() && this.bundle.env.outputFormat === 'global') ||
180
+ (!this.isEntry() && this.bundle.env.outputFormat !== 'commonjs') ||
165
181
  this.bundle.env.sourceType === 'script'
166
182
  ) {
167
183
  // In async bundles we don't want the main entry to execute until we require it
@@ -170,6 +186,13 @@ export class DevPackager {
170
186
  mainEntry = null;
171
187
  }
172
188
 
189
+ if (usedHelpers & 4) {
190
+ prefix = prefix.replace(
191
+ '// INSERT_LOAD_HERE',
192
+ 'newRequire.load = function (url) { return import(distDir + "/" + url); }',
193
+ );
194
+ }
195
+
173
196
  let contents =
174
197
  prefix +
175
198
  '({' +
@@ -183,9 +206,24 @@ export class DevPackager {
183
206
  mainEntry ? this.bundleGraph.getAssetPublicId(mainEntry) : null,
184
207
  ) +
185
208
  ', ' +
186
- JSON.stringify(this.parcelRequireName) +
187
- ')' +
188
- '\n';
209
+ JSON.stringify(this.parcelRequireName);
210
+
211
+ if (usedHelpers & 1) {
212
+ // Generate a relative path from this bundle to the root of the dist dir.
213
+ let distDir = relativePath(path.dirname(this.bundle.name), '');
214
+ if (distDir.endsWith('/')) {
215
+ distDir = distDir.slice(0, -1);
216
+ }
217
+ contents += ', ' + JSON.stringify(distDir);
218
+ } else if (usedHelpers & 2) {
219
+ contents += ', null';
220
+ }
221
+
222
+ if (usedHelpers & 2) {
223
+ contents += ', ' + JSON.stringify(this.bundle.target.publicUrl);
224
+ }
225
+
226
+ contents += ')\n';
189
227
 
190
228
  // The entry asset of a script bundle gets hoisted outside the bundle wrapper function
191
229
  // so that its variables become globals. We need to replace any require calls for
@@ -232,6 +270,14 @@ export class DevPackager {
232
270
  b,
233
271
  )}");\n`;
234
272
  }
273
+ } else if (this.bundle.env.isNode()) {
274
+ let bundles = this.bundleGraph.getReferencedBundles(this.bundle);
275
+ for (let b of bundles) {
276
+ if (b.type !== 'js') {
277
+ continue;
278
+ }
279
+ importScripts += `require("${relativeBundlePath(this.bundle, b)}");\n`;
280
+ }
235
281
  }
236
282
 
237
283
  return (
@@ -40,21 +40,28 @@ const REPLACEMENT_RE =
40
40
  /\n|import\s+"([0-9a-f]{16}:.+?)";|(?:\$[0-9a-f]{16}\$exports)|(?:\$[0-9a-f]{16}\$(?:import|importAsync|require)\$[0-9a-f]+(?:\$[0-9a-f]+)?)/g;
41
41
 
42
42
  const BUILTINS = Object.keys(globals.builtin);
43
+ const BROWSER_BUILTINS = new Set([
44
+ ...BUILTINS,
45
+ ...Object.keys(globals.browser),
46
+ ]);
47
+ const NODE_BUILTINS = new Set([...BUILTINS, ...Object.keys(globals.node)]);
43
48
  const GLOBALS_BY_CONTEXT = {
44
- browser: new Set([...BUILTINS, ...Object.keys(globals.browser)]),
49
+ browser: BROWSER_BUILTINS,
50
+ 'react-client': BROWSER_BUILTINS,
45
51
  'web-worker': new Set([...BUILTINS, ...Object.keys(globals.worker)]),
46
52
  'service-worker': new Set([
47
53
  ...BUILTINS,
48
54
  ...Object.keys(globals.serviceworker),
49
55
  ]),
50
56
  worklet: new Set([...BUILTINS]),
51
- node: new Set([...BUILTINS, ...Object.keys(globals.node)]),
52
- 'electron-main': new Set([...BUILTINS, ...Object.keys(globals.node)]),
57
+ node: NODE_BUILTINS,
58
+ 'electron-main': NODE_BUILTINS,
53
59
  'electron-renderer': new Set([
54
60
  ...BUILTINS,
55
61
  ...Object.keys(globals.node),
56
62
  ...Object.keys(globals.browser),
57
63
  ]),
64
+ 'react-server': NODE_BUILTINS,
58
65
  };
59
66
 
60
67
  const OUTPUT_FORMATS = {
@@ -131,12 +138,15 @@ export class ScopeHoistingPackager {
131
138
  // picked up by another bundler later at which point runtimes will be added.
132
139
  if (
133
140
  this.bundle.env.isLibrary ||
134
- this.bundle.env.outputFormat === 'commonjs'
141
+ this.bundle.env.outputFormat === 'commonjs' ||
142
+ (this.bundle.env.outputFormat === 'esmodule' && !this.isAsyncBundle)
135
143
  ) {
136
144
  for (let b of this.bundleGraph.getReferencedBundles(this.bundle, {
137
145
  recursive: false,
138
146
  })) {
139
- this.externals.set(relativeBundlePath(this.bundle, b), new Map());
147
+ if (this.bundle.env.isLibrary || b.type === 'js') {
148
+ this.externals.set(relativeBundlePath(this.bundle, b), new Map());
149
+ }
140
150
  }
141
151
  }
142
152
 
@@ -374,7 +384,11 @@ export class ScopeHoistingPackager {
374
384
  // If the module has a namespace (e.g. commonjs), and this is not an entry, only export the namespace
375
385
  // as default, without individual exports. This mirrors the importing logic in addExternal, avoiding
376
386
  // extra unused exports and potential for non-identifier export names.
377
- if (hasNamespace && this.isAsyncBundle && exportAs !== '*') {
387
+ if (
388
+ hasNamespace &&
389
+ !this.bundle.needsStableName &&
390
+ exportAs !== '*'
391
+ ) {
378
392
  continue;
379
393
  }
380
394
 
@@ -502,6 +516,19 @@ export class ScopeHoistingPackager {
502
516
  this.usedHelpers.add('$parcel$global');
503
517
  }
504
518
 
519
+ let usedHelpers = asset.meta.usedHelpers;
520
+ if (typeof usedHelpers === 'number') {
521
+ if (usedHelpers & 1) {
522
+ this.usedHelpers.add('$parcel$distDir');
523
+ }
524
+ if (usedHelpers & 2) {
525
+ this.usedHelpers.add('$parcel$publicUrl');
526
+ }
527
+ if (usedHelpers & 4) {
528
+ this.usedHelpers.add('$parcel$import');
529
+ }
530
+ }
531
+
505
532
  if (this.bundle.env.isNode() && asset.meta.has_node_replacements) {
506
533
  const relPath = normalizeSeparators(
507
534
  path.relative(this.bundle.target.distDir, path.dirname(asset.filePath)),
@@ -1357,7 +1384,7 @@ ${code}
1357
1384
  for (let helper of this.usedHelpers) {
1358
1385
  let currentHelper = helpers[helper];
1359
1386
  if (typeof currentHelper === 'function') {
1360
- currentHelper = helpers[helper](this.bundle.env);
1387
+ currentHelper = helpers[helper](this.bundle.env, this.bundle);
1361
1388
  }
1362
1389
  res += currentHelper;
1363
1390
  if (enableSourceMaps) {
@@ -6,7 +6,7 @@
6
6
  // anything defined in a previous bundle is accessed via the
7
7
  // orig method which is the require for previous bundles
8
8
 
9
- (function (modules, entry, mainEntry, parcelRequireName, globalName) {
9
+ (function (modules, entry, mainEntry, parcelRequireName, distDir, publicUrl) {
10
10
  /* eslint-disable no-undef */
11
11
  var globalObject =
12
12
  typeof globalThis !== 'undefined'
@@ -101,6 +101,8 @@
101
101
  newRequire.modules = modules;
102
102
  newRequire.cache = cache;
103
103
  newRequire.parent = previousRequire;
104
+ newRequire.distDir = distDir;
105
+ newRequire.publicUrl = publicUrl;
104
106
  newRequire.register = function (id, exports) {
105
107
  modules[id] = [
106
108
  function (require, module) {
@@ -110,6 +112,10 @@
110
112
  ];
111
113
  };
112
114
 
115
+ // Only insert newRequire.load when it is actually used.
116
+ // The code in this file is linted against ES5, so dynamic import is not allowed.
117
+ // INSERT_LOAD_HERE
118
+
113
119
  Object.defineProperty(newRequire, 'root', {
114
120
  get: function () {
115
121
  return globalObject[parcelRequireName];
@@ -136,10 +142,6 @@
136
142
  define(function () {
137
143
  return mainExports;
138
144
  });
139
-
140
- // <script>
141
- } else if (globalName) {
142
- this[globalName] = mainExports;
143
145
  }
144
146
  }
145
147
  });
package/src/helpers.js CHANGED
@@ -1,5 +1,7 @@
1
1
  // @flow strict-local
2
- import type {Environment} from '@parcel/types';
2
+ import type {Environment, NamedBundle} from '@parcel/types';
3
+ import {relativePath} from '@parcel/utils';
4
+ import path from 'path';
3
5
 
4
6
  export const prelude = (parcelRequireName: string): string => `
5
7
  var $parcel$modules = {};
@@ -160,10 +162,36 @@ function $parcel$defineInteropFlag(a) {
160
162
  }
161
163
  `;
162
164
 
165
+ const $parcel$distDir = (env: Environment, bundle: NamedBundle): string => {
166
+ // Generate a relative path from this bundle to the root of the dist dir.
167
+ let distDir = relativePath(path.dirname(bundle.name), '');
168
+ if (distDir.endsWith('/')) {
169
+ distDir = distDir.slice(0, -1);
170
+ }
171
+ return `var $parcel$distDir = ${JSON.stringify(distDir)};\n`;
172
+ };
173
+
174
+ const $parcel$publicUrl = (env: Environment, bundle: NamedBundle): string => {
175
+ return `var $parcel$publicUrl = ${JSON.stringify(
176
+ bundle.target.publicUrl,
177
+ )};\n`;
178
+ };
179
+
180
+ const $parcel$import = (env: Environment): string => {
181
+ return `var $parcel$import = ${fnExpr(
182
+ env,
183
+ ['url'],
184
+ ['return import($parcel$distDir + "/" + url);'],
185
+ )};\n`;
186
+ };
187
+
163
188
  export const helpers = {
164
189
  $parcel$export,
165
190
  $parcel$exportWildcard,
166
191
  $parcel$interopDefault,
167
192
  $parcel$global,
168
193
  $parcel$defineInteropFlag,
194
+ $parcel$distDir,
195
+ $parcel$publicUrl,
196
+ $parcel$import,
169
197
  };