Skip to content

Commit 97c5883

Browse files
authored
Fix dynamic fetching npm modules for conflicting libraries (codesandbox#500)
* Fix dynamic fetching npm modules for conflicting libraries * Fix main vs module field
1 parent f284f43 commit 97c5883

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

packages/app/src/sandbox/eval/manager.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,14 @@ export default class Manager {
377377
extensions: defaultExtensions.map(ext => '.' + ext),
378378
isFile: this.isFile,
379379
readFileSync: this.readFileSync,
380+
packageFilter: p => {
381+
if (!p.main && p.module) {
382+
// eslint-disable-next-line
383+
p.main = p.module;
384+
}
385+
386+
return p;
387+
},
380388
moduleDirectory: ['node_modules', this.envVariables.NODE_PATH].filter(
381389
x => x
382390
),

packages/app/src/sandbox/eval/npm/fetch-npm-module.js

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,21 @@ function normalize(
5050
return fileObject;
5151
}
5252

53+
function getUnpkgUrl(name: string, version: string) {
54+
const nameWithoutAlias = name.replace(/\/\d*\.\d*\.\d*$/, '');
55+
56+
return `https://unpkg.com/${nameWithoutAlias}@${version}`;
57+
}
58+
5359
function getMeta(name: string, version: string) {
54-
const id = `${name}@${version}`;
60+
const nameWithoutAlias = name.replace(/\/\d*\.\d*\.\d*$/, '');
61+
const id = `${nameWithoutAlias}@${version}`;
5562
if (metas[id]) {
5663
return metas[id];
5764
}
5865

5966
metas[id] = window
60-
.fetch(`https://unpkg.com/${name}@${version}/?meta`)
67+
.fetch(`https://unpkg.com/${nameWithoutAlias}@${version}/?meta`)
6168
.then(x => x.json());
6269

6370
return metas[id];
@@ -76,9 +83,10 @@ function downloadDependency(depName: string, depVersion: string, path: string) {
7683
);
7784

7885
const isGitHub = /\//.test(depVersion);
86+
7987
const url = isGitHub
8088
? `https://cdn.jsdelivr.net/gh/${depVersion}${relativePath}`
81-
: `https://unpkg.com/${depName}@${depVersion}${relativePath}`;
89+
: `${getUnpkgUrl(depName, depVersion)}${relativePath}`;
8290

8391
packages[path] = window
8492
.fetch(url)
@@ -112,6 +120,14 @@ function resolvePath(
112120
{
113121
filename: currentPath,
114122
extensions: defaultExtensions.map(ext => '.' + ext),
123+
packageFilter: p => {
124+
if (!p.main && p.module) {
125+
// eslint-disable-next-line
126+
p.main = p.module;
127+
}
128+
129+
return p;
130+
},
115131
moduleDirectory: [
116132
'node_modules',
117133
manager.envVariables.NODE_PATH,

0 commit comments

Comments
 (0)