首页 > 解决方案 > 我的包在 CodeSandBox 上导入时给出“ModuleNotFoundError”

问题描述

我今天发布了一个 npm 包,想在 CodeSandBox 上尝试一下。如果我npm install package-name在本地机器上但在 CodeSandBox 项目上导入相同的依赖项会出现此错误,则它可以工作:

包.json

{
  "name": "package-name",
  "version": "1.0.20",
  "private": false,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.1",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "NODE_ENV=production babel src/lib --out-dir dist --copy-files --ignore __tests__,spec.js,test.js,__snapshots__",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "keywords": [
    "react"
  ],
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "main": "dist/index.js",
  "module": "dist/index.js",
  "files": [
    "dist",
    "README.md"
  ],
  "repository": {
    "type": "git",
  },
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.8.4",
    "@babel/runtime": "^7.8.4"
  }
}

我编译的文件在顶部有这些类型的导入:

import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";

我按照教程进行操作。运行后,会在主目录中创建npm run build一个文件夹。dist然后我npm publish。我确实npm install package-name在本地机器上尝试过,它可以工作,但正如我所说,它在 CodeSandBox 上不起作用。

标签: node.jsreactjsnpmbabeljs

解决方案


尝试将您添加devDependenciesdependencies. devDependencies没有在构建中导出,这就是为什么你可能babel/runtime失败了。

 "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.1",
    "@testing-library/user-event": "^7.2.1",
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.8.4",
    "@babel/runtime": "^7.8.4",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.4.0"
  }

然后构建并尝试。


推荐阅读