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 字段
相关推荐
u0111026751 小时前
JPG、PNG、WebP 怎么选?按透明度、体积和使用场景做判断
前端·javascript·vue.js·图像处理·ai作画
jerrywus2 小时前
让 AI 写完代码后交一份报告:我改造了 answer-me-with-html
前端·claude·cursor
派小心.2 小时前
小程序分享链路中来源参数的传递校验
大数据·前端·数据库·人工智能·小程序·数据分析
hhb_6182 小时前
一键生成数据看板,ECharts实战演示
前端·javascript·echarts
Java后端的Ai之路2 小时前
08_React组件API
前端·react.js·前端框架
小马不起床3 小时前
零基础玩转 FastAPI_09:前端基础工程构建
前端·状态模式·fastapi
风骏时光牛马4 小时前
用户管理模块接口开发
前端
彭亚川Allen4 小时前
从零手搓 RAG 之检索全流程,给大模型接上自己的知识库
前端·后端·ai编程
IT_陈寒4 小时前
别让Java字符串拼接偷偷吃掉你的内存
前端·人工智能·后端
软件技术NINI5 小时前
圣罗兰彩妆html+css 4页
前端·css·html