|
1 | 1 | import type { DepsHandlingOptions } from './types' |
2 | 2 | import { existsSync, promises as fsp } from 'node:fs' |
| 3 | +import * as esModuleLexer from 'es-module-lexer' |
3 | 4 | import { dirname, extname, join } from 'pathe' |
4 | 5 | import { KNOWN_ASSET_RE } from './constants' |
5 | 6 | import { findNearestPackageData, isNodeBuiltin, slash } from './utils' |
6 | 7 |
|
7 | 8 | const BUILTIN_EXTENSIONS = new Set(['.mjs', '.cjs', '.node', '.wasm']) |
8 | 9 |
|
9 | | -const ESM_SYNTAX_RE |
10 | | - = /(?:[\s;]|^)(?:import[\s\w*,{}]*from|import\s*["'*{]|export\b\s*(?:[*{]|default|class|type|function|const|var|let|async function)|import\.meta\b)/m |
11 | 10 | const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/ |
12 | 11 | const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/ |
13 | 12 |
|
14 | | -// https://stackoverflow.com/a/15123777 |
15 | | -const COMMENT_RE = /\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm |
16 | | - |
17 | 13 | const defaultInline = [ |
18 | 14 | /virtual:/, |
19 | 15 | /\.[mc]?ts$/, |
@@ -80,9 +76,15 @@ async function isValidNodeImport(id: string) { |
80 | 76 | return false |
81 | 77 | } |
82 | 78 |
|
83 | | - const code = await fsp.readFile(id, 'utf8').catch(() => '') |
84 | | - |
85 | | - return !ESM_SYNTAX_RE.test(code.replace(COMMENT_RE, '')) |
| 79 | + try { |
| 80 | + await esModuleLexer.init |
| 81 | + const code = await fsp.readFile(id, 'utf8') |
| 82 | + const [, , , hasModuleSyntax] = esModuleLexer.parse(code) |
| 83 | + return !hasModuleSyntax |
| 84 | + } |
| 85 | + catch { |
| 86 | + return false |
| 87 | + } |
86 | 88 | } |
87 | 89 |
|
88 | 90 | const _defaultExternalizeCache = new Map<string, Promise<string | false>>() |
|
0 commit comments