Failed to resolve entry for package "js-demo-tools". The package may have ......

背景:在我自己开发的npm包,上传到了npm之后,测试的时候使用vite框架进行导入这个包报的错误

json 复制代码
{
  "name": "xxx-demo",
  "version": "1.0.0",
  "description": "this is learn npm package",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "build": "rollup -c"
  },
  "files": [
    "/dist"
  ],
  "keywords": [],
  "author": "",
  "license": "ISC",
  "packageManager": "pnpm@10.14.0",
  "devDependencies": {
    "rollup": "^4.46.4",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.36.0"
  }
}
  1. main 字段指向错误"main": "index.js" 指向根目录的 index.js,但我的 files 配置只包含 /dist 文件夹,所以发布到 npm 的包中根本没有根目录的 index.js文件。

  2. 缺少 ES 模块入口配置 :虽然你设置了 "type": "module",但没有配置 module 字段或现代的 exports 字段来指定 ES 模块的入口点。

  3. Vite 无法找到正确的入口:Vite 作为现代构建工具,优先查找 ES 模块入口,但你的配置没有提供正确的路径。

推荐 直接使用 exports 字段

json 复制代码
{
  "name": "xxx-demo",
  "version": "1.0.0",
  "description": "this is learn npm package",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "build": "rollup -c"
  },
  "files": [
    "/dist"
  ],
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.cjs"
    }
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "packageManager": "pnpm@10.14.0",
  "devDependencies": {
    "rollup": "^4.46.4",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-terser": "^7.0.2",
    "rollup-plugin-typescript2": "^0.36.0"
  }
}

为什么推荐呢?

  1. 现代标准exports 字段是 Node.js 和现代打包工具的标准
  2. 明确的入口点:清楚地指定了不同模块系统的入口
  3. 更好的兼容性:同时支持 ES 模块和 CommonJS
  4. Vite 友好 :Vite 会优先查找 exports.import 字段
相关推荐
aiwery2 分钟前
大模型场景下的推送技术选型:轮询 vs WebSocket vs SSE
前端·agent
会豪3 分钟前
前端插件-不固定高度的DIV如何增加transition
前端
却尘3 分钟前
Server Actions 深度剖析(2):缓存管理与重新验证,如何用一行代码干掉整个客户端状态层
前端·客户端·next.js
小菜全3 分钟前
Vue 3 + TypeScript 事件触发与数据绑定方法
前端·javascript·vue.js
Hilaku7 分钟前
面试官开始问我AI了,前端的危机真的来了吗?
前端·javascript·面试
shellvon1 小时前
前端攻防:揭秘 Chrome DevTools 与反调试的博弈
前端·逆向
β添砖java1 小时前
案例二:登高千古第一绝句
前端·javascript·css
却尘1 小时前
Server Actions 深度剖析:这就是个披着 React 外衣的 RPC
前端·rpc·next.js
南雨北斗1 小时前
Vue 3 修饰符(Modifiers)
前端
会豪1 小时前
工业仿真(simulation)--前端(七)--消息栏
前端