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

开发ES模块类型npm包时出现Cannot find module错误,如何解决?

问题:导入自定义npm包playwrightlib时出现模块找不到错误

问题背景

我开发了一个名为playwrightlib的npm包,相关配置和代码如下:

package.json配置

{
  "name": "playwrightlib",
  "version": "0.0.7",
  "description": "Lib with playwright dependency",
  "repository": "git@github.com:DonTomato/playwrightlib.git",
  "author": "myemail@gmail.com",
  "license": "MIT",
  "type": "module",
  "exports": "./src/index.js",
  "files": [
    "src",
    "*.md"
  ],
  "engines": {
    "node": "^16.15.0"
  },
  "dependencies": {
    "jest": "^29.5.0",
    "@playwright/test": "^1.28.1"
  }
}

包内文件结构及代码

src目录下包含两个文件:

  • index.js:
export { testAbout } from './actions';
  • actions.js:
import { expect } from '@playwright/test';

/**
 * test About page
 * @param {object} page - current page
 */
export async function testAbout(page) {
  await page.goto('/about');
  await expect(page.getByRole('heading', { name: 'About this app' })).toBeVisible();
}

报错信息

当使用import { testAbout } from 'playwrightlib';导入该包时,出现如下错误:

Error: Cannot find module 'C:...\\node_modules\\playwrightlib\\src\\actions' imported from C:...\\node_modules\\playwrightlib\\src\\index.js

原因分析

在ES模块(type: module)规范中,导入相对路径的模块时必须指定完整的文件扩展名。当前index.js中使用./actions导入,Node.js会尝试寻找名为actions的目录或actions.node文件,而不会自动补全.js扩展名,因此无法找到对应的actions.js文件。

解决方法

修改src/index.js中的导入语句,添加完整的.js扩展名:

export { testAbout } from './actions.js';

重新打包发布npm包,或在本地测试时重新安装该包,即可解决模块找不到的问题。


内容的提问来源于stack exchange,提问作者Don Tomato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:23:42