Skip to content

Commit fb760de

Browse files
committed
fix(@ngtools/webpack): fix resolution fallback of paths-plugin
If there is a package.json we should also verify that it has a main or fesm field to see if webpack would actually resolve it properly. Otherwise use the JavaScript resolution. This is a temporary fix and still has obvious limitations and issues. Namely, this code is never run if there is only one path mapping, but that falls outside the scope of this fix. Also, some people might have valid packages but want to resolve to the JS file itself (which is what TypeScript does by default). These should be fixed with a refactoring of the path plugin. Fixes NativeScript/nativescript-dev-webpack#607
1 parent 583ccd2 commit fb760de

1 file changed

Lines changed: 33 additions & 8 deletions

File tree

‎src/paths-plugin.ts‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -160,15 +160,40 @@ export function resolveWithPaths(
160160
const jsFilePath = `${pathNoExtension}.js`;
161161

162162
if (host.fileExists(pathNoExtension)) {
163-
// This is mainly for secondary entry points
164-
// ex: 'node_modules/@angular/core/testing.d.ts' -> 'node_modules/@angular/core/testing'
165-
request.request = pathNoExtension;
166-
} else if (host.fileExists(packageRootPath)) {
167-
// Let webpack resolve the correct module format
168-
request.request = pathDirName;
169-
} else if (host.fileExists(jsFilePath)) {
163+
// This is mainly for secondary entry points
164+
// ex: 'node_modules/@angular/core/testing.d.ts' -> 'node_modules/@angular/core/testing'
165+
request.request = pathNoExtension;
166+
} else {
167+
const packageJsonContent = host.readFile(packageRootPath);
168+
let newRequest: string | undefined;
169+
170+
if (packageJsonContent) {
171+
try {
172+
const packageJson = JSON.parse(packageJsonContent);
173+
174+
// Let webpack resolve the correct module format IIF there is a module resolution field
175+
// in the package.json. These are all official fields that Angular uses.
176+
if (typeof packageJson.main == 'string'
177+
|| typeof packageJson.browser == 'string'
178+
|| typeof packageJson.module == 'string'
179+
|| typeof packageJson.es2015 == 'string'
180+
|| typeof packageJson.fesm5 == 'string'
181+
|| typeof packageJson.fesm2015 == 'string') {
182+
newRequest = pathDirName;
183+
}
184+
} catch {
185+
// Ignore exceptions and let it fall through (ie. if package.json file is invalid).
186+
}
187+
}
188+
189+
if (newRequest === undefined && host.fileExists(jsFilePath)) {
170190
// Otherwise, if there is a file with a .js extension use that
171-
request.request = jsFilePath;
191+
newRequest = jsFilePath;
192+
}
193+
194+
if (newRequest !== undefined) {
195+
request.request = newRequest;
196+
}
172197
}
173198

174199
callback(null, request);

0 commit comments

Comments
 (0)