Skip to content

Commit

Permalink
fix: improve esm detection with export declartion (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu authored Dec 17, 2021
1 parent 660d0ad commit 0511a93
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/syntax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'])

Expand Down Expand Up @@ -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)
}
4 changes: 3 additions & 1 deletion test/syntax.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down

0 comments on commit 0511a93

Please sign in to comment.