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

React组件NPM包从私有Bitbucket安装后无法导入的问题排查

问题

我正在开发一个可在其他项目中使用的小型React组件包,目前我的package.json配置如下:

{
  "name": "my-package",
  "version": "0.1.1",
  "private": true,
  "main": "./dist/lib.umd.js",
  "module": "./dist/lib.module.js",
  "source": "src/components/MyPackage/index.js",
  "exports": {
    ".": "./dist/lib.js",
    "./styles.css": "./dist/lib.css"
  },
  "dependencies": {
    "classnames": "^2.3.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "microbundle": "^0.15.0",
    "react-scripts": "5.0.1"
  },
  "peerDependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "microbundle --jsx React.createElement --jsxFragment React.Fragment --jsxImportSource react",
    "watch": "microbundle watch --jsx React.createElement --jsxFragment React.Fragment --jsxImportSource react"
  },
  "eslintConfig": {
    "extends": [
      "react-app"
    ]
  },
  "files": [
    "dist"
  ],
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

其中exports、module和source字段用于告知microbundle打包内容及路径。

该仓库托管在私有Bitbucket中,我通过npm i git+ssh://git@bitbucket.org:myuser/mypackage.git命令安装此包,但无法导入。查看node_modules/mypackage目录,仅包含package.json和README文件,没有JS文件;本地使用npm link导入时该包可正常工作。请问需要如何配置package.json才能解决此问题?

解决方案
  • 移除private: true字段:private: true会阻止npm处理包的安装构建流程,删除后npm才能正常识别并处理这个包。
  • 提交dist目录到Git仓库:通过Git URL安装时,npm只会拉取仓库中已提交的文件。如果.gitignore里忽略了dist,需要移除该规则,执行git add dist && git commit把构建产物提交到仓库。
  • 添加prepare自动构建脚本:在scripts中新增"prepare": "npm run build",这个脚本会在npm install(包括从Git安装)时自动执行,确保安装后生成dist目录。
  • 统一exports字段路径:当前exports指向的./dist/lib.js和main、module的文件不一致,建议调整为:
    "exports": {
      ".": {
        "import": "./dist/lib.module.js",
        "require": "./dist/lib.umd.js"
      },
      "./styles.css": "./dist/lib.css"
    }
    
    这样能适配ES模块和CommonJS两种导入场景,避免路径混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:27:31