Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,11 @@ export function checkCommonJSModules(
continue;
}

// Check if the import is ESM format and issue a diagnostic if the file is not allowed
if (metafile.inputs[imported.path].format !== 'esm') {
// Check if non-relative import is ESM format and issue a diagnostic if the file is not allowed
if (
!isPotentialRelative(imported.original) &&
metafile.inputs[imported.path].format !== 'esm'
) {
const request = imported.original;

let notAllowed = true;
Expand Down Expand Up @@ -119,6 +122,23 @@ function isPathCode(name: string): boolean {
return /\.[cm]?[jt]sx?$/.test(name);
}

/**
* Test an import module specifier to determine if the string potentially references a relative file.
* npm packages should not start with a period so if the first character is a period than it is not a
* package. While this is sufficient for the use case in the CommmonJS checker, only checking the
* first character does not definitely indicate the specifier is a relative path.
*
* @param specifier An import module specifier.
* @returns True, if specifier is potentially relative; false, otherwise.
*/
function isPotentialRelative(specifier: string): boolean {
if (specifier[0] === '.') {
Copy link
Collaborator

@alan-agius4 alan-agius4 May 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can be changed to just return specifier[0] === '.'

return true;
}

return false;
}

/**
* Creates an esbuild diagnostic message for a given non-ESM module request.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,5 +159,25 @@ describeBuilder(buildEsbuildBrowser, BROWSER_BUILDER_INFO, (harness) => {
}),
);
});

it('should not show warning for relative imports', async () => {
await harness.appendToFile('src/main.ts', `import './abc';`);
await harness.writeFile('src/abc.ts', 'console.log("abc");');

harness.useTarget('build', {
...BASE_OPTIONS,
allowedCommonJsDependencies: [],
optimization: true,
});

const { result, logs } = await harness.executeOnce();

expect(result?.success).toBe(true);
expect(logs).not.toContain(
jasmine.objectContaining<logging.LogEntry>({
message: jasmine.stringMatching(/CommonJS or AMD dependencies/),
}),
);
});
});
});