From 0511a93d3565f3a2a6679fc09a3e6ce349724478 Mon Sep 17 00:00:00 2001 From: Anthony Fu Date: Fri, 17 Dec 2021 17:01:08 +0800 Subject: [PATCH] fix: improve esm detection with export declartion (#27) --- src/syntax.ts | 4 ++-- test/syntax.test.mjs | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/syntax.ts b/src/syntax.ts index 781c192..8ecb06a 100644 --- a/src/syntax.ts +++ b/src/syntax.ts @@ -5,7 +5,7 @@ import { ResolveOptions, resolvePath } from './resolve' import { isNodeBuiltin } from './utils' import { getProtocol } from './_utils' -const ESM_RE = /([\s;]|^)(import[\w,{}\s*]*from|import\s*['"*{]|export\b\s*([*{]|default|type)|import\.meta\b)/m +const ESM_RE = /([\s;]|^)(import[\w,{}\s*]*from|import\s*['"*{]|export\b\s*(?:[*{]|default|type|function|const|var|let|async function)|import\.meta\b)/m const BUILTIN_EXTENSIONS = new Set(['.mjs', '.cjs', '.node', '.wasm']) @@ -82,7 +82,7 @@ export async function isValidNodeImport (id: string, _opts: ValidNodeImportOptio const pkg = await readPackageJSON(resolvedPath).catch(() => null) if (pkg?.type === 'module') { return true } - const code = opts.code || await fsp.readFile(resolvedPath, 'utf-8').catch(() => null) + const code = opts.code || await fsp.readFile(resolvedPath, 'utf-8').catch(() => null) || '' return hasCJSSyntax(code) || !hasESMSyntax(code) } diff --git a/test/syntax.test.mjs b/test/syntax.test.mjs index b87d9c6..8f87f1d 100644 --- a/test/syntax.test.mjs +++ b/test/syntax.test.mjs @@ -14,10 +14,12 @@ const staticTests = { 'import defaultExport, { export1, export2 } from "module-name";': { hasESM: true, hasCJS: false, isMixed: false }, 'import defaultExport, * as name from"module-name";': { hasESM: true, hasCJS: false, isMixed: false }, 'import"module-name"': { hasESM: true, hasCJS: false, isMixed: false }, - // 'import defaultMember from "module-name";': { hasESM: true, hasCJS: false, isMixed: false }, 'import "./file.mjs"': { hasESM: true, hasCJS: false, isMixed: false }, 'export default b=""': { hasESM: true, hasCJS: false, isMixed: false }, + 'export const a = 1': { hasESM: true, hasCJS: false, isMixed: false }, + 'export function hi() {}': { hasESM: true, hasCJS: false, isMixed: false }, + 'export async function foo() {}': { hasESM: true, hasCJS: false, isMixed: false }, // CJS 'exports.c={}': { hasESM: false, hasCJS: true, isMixed: false }, 'const b=true;module.exports={b};': { hasESM: false, hasCJS: true, isMixed: false },