You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在外部.mjs脚本中使用项目本地的node_modules依赖

问题核心

ES模块(.mjs)遵循ES模块规范,不支持NODE_PATH环境变量——这个变量是CommonJS模块解析机制的特性,所以你之前的配置无法生效。

解决方案

方法1:启用CommonJS风格模块解析

通过--experimental-specifier-resolution=node参数让Node.js使用CommonJS的模块解析逻辑,此时NODE_PATH会被识别。

在/project目录下执行:

NODE_PATH=$(pwd)/node_modules node --experimental-specifier-resolution=node ../scripts/my-script.mjs

方法2:用npm exec/npx执行脚本

npm exec(或npx)会自动将当前项目的node_modules加入模块查找路径,无需额外配置环境变量。

在/project目录下执行:

npm exec -- node ../scripts/my-script.mjs

或:

npx -- node ../scripts/my-script.mjs

方法3:混合模块导入(ES+CommonJS)

在.mjs脚本中创建CommonJS风格的require函数,借助它利用NODE_PATH解析模块:

修改my-script.mjs的导入代码:

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { Project, SyntaxKind } = require('ts-morph');

之后执行你原来的命令即可:

NODE_PATH=$(pwd)/node_modules node ../scripts/my-script.mjs

方法4:绝对路径导入(不推荐)

直接在脚本中指定ts-morph的绝对路径,缺点是路径固定,换环境需手动修改:

import { Project, SyntaxKind } from '/your/absolute/path/project/node_modules/ts-morph';

内容的提问来源于stack exchange,提问作者Jeanluca Scaljeri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 03:49:55