Neovim DAP调试TypeScript触发loadESM错误求助
解决Neovim DAP调试TypeScript时的ESM加载错误
你遇到的loadESM错误确实和ESM模块加载配置相关,以下是几个针对性的修复方案:
方案一:修正ts-node的ESM加载配置
你的runtimeArgs配置缺少ESM模式下的必要参数,修改后配置如下:
{ type = 'pwa-node', request = 'launch', name = 'Launch Current File (pwa-node with ts-node)', cwd = vim.fn.getcwd(), runtimeArgs = { '--experimental-loader', 'ts-node/esm', '--experimental-specifier-resolution=node' }, runtimeExecutable = 'node', args = { '${file}' }, sourceMaps = true, protocol = 'inspector', skipFiles = { '<node_internals>/**', 'node_modules/**' }, resolveSourceMapLocations = { "${workspaceFolder}/**", "!**/node_modules/**", }, program = '${file}', outFiles = { "${workspaceFolder}/**/*.js" }, }
--experimental-specifier-resolution=node用于让Node.js兼容CommonJS风格的模块解析,program和outFiles则帮助调试器正确关联TS源文件和生成的JS文件。
方案二:改用tsx替代ts-node
tsx对ESM的支持更轻量化,无需额外配置,先全局安装tsx:
npm install -g tsx
然后替换DAP配置:
{ type = 'pwa-node', request = 'launch', name = 'Launch Current File (pwa-node with tsx)', cwd = vim.fn.getcwd(), runtimeExecutable = 'tsx', args = { '${file}' }, sourceMaps = true, protocol = 'inspector', skipFiles = { '<node_internals>/**', 'node_modules/**' }, resolveSourceMapLocations = { "${workspaceFolder}/**", "!**/node_modules/**", }, }
方案三:检查项目的模块模式配置
- 如果项目是ESM模式(
package.json含"type": "module"),确保tsconfig.json的编译配置匹配:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", "target": "ES2020", "sourceMap": true } }
- 如果是CommonJS模式,删除
package.json中的"type": "module",并将tsconfig.json的module设为CommonJS。
方案四:拆分JS/TS的调试配置
第一个纯pwa-node配置无法直接调试TS文件,建议拆分配置,仅给JS/JSX使用该方案:
-- JS/JSX专属调试配置 local js_exts = { 'javascript', 'javascriptreact' } for _, ext in ipairs(js_exts) do dap.configurations[ext] = { { type = 'pwa-node', request = 'launch', name = 'Launch Current File (pwa-node)', cwd = vim.fn.getcwd(), args = { '${file}' }, sourceMaps = true, protocol = 'inspector', } } end -- TS/TSX专属调试配置 local ts_exts = { 'typescript', 'typescriptreact' } for _, ext in ipairs(ts_exts) do dap.configurations[ext] = { -- 此处放入方案一或方案二的配置 } end
内容的提问来源于stack exchange,提问作者VladTbk321
相关产品推荐
相关产品推荐

