首页 > 解决方案 > 必须使用 import 在已安装的库上加载 ES 模块

问题描述

我已经建立了一个库,并将其安装并导入到项目中,当我尝试运行导入的模块时:

import buildSitemap from 'react-build-sitemap'

我收到以下错误:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/corey/work/CloudHospital.Front/node_modules/react-build-sitemap/index.js
require() of ES modules is not supported.
require() of /home/corey/work/CloudHospital.Front/node_modules/react-build-sitemap/index.js from /home/corey/work/CloudHospital.Front/build/server.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/corey/work/CloudHospital.Front/node_modules/react-build-sitemap/package.json.

我试图"type": "module"package.json导入的库中删除,但仍然收到相同的错误。不太确定如何通过导入来解决此问题(我要导入的文件是一个打字稿文件,如果这有什么不同的话——它不应该,因为所有内容都是为我正在导入的库正确键入的):

从图书馆的index.js

import babelParser from "@babel/parser";
import fs from "fs";
import PropTypes from "prop-types";
import { warn } from "console";

和 package.json:

{
  "name": "react-build-sitemap",
  "version": "0.1.9",
  "description": "simple library that generates a sitemap from your react router",
  "main": "./index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "babel-node index.js"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/lanierc/react-build-sitemap.git"
  },
  "keywords": [
    "react",
    "react-router",
    "sitemap",
    "build",
    "generate"
  ],
  "author": "Corey Lanier <corey@icloudhospital.com>",
  "license": "GPL-3.0-or-later",
  "bugs": {
    "url": "https://github.com/lanierc/react-build-sitemap/issues"
  },
  "homepage": "https://github.com/lanierc/react-build-sitemap#readme",
  "dependencies": {
    "fs": "0.0.1-security",
    "prop-types": "^15.7.2",
    "react": "^16.13.1",
    "react-router": "^5.2.0"
  },
  "peerDependencies": {
    "react": "^16.13.1",
    "react-router": "^5.2.0"
  },
  "devDependencies": {
    "@babel/core": "^7.11.1",
    "@babel/node": "^7.10.5",
    "@babel/parser": "^7.11.3",
    "@babel/plugin-syntax-jsx": "^7.10.4",
    "@babel/preset-react": "^7.10.4",
    "babel-plugin-jsx": "^1.2.0",
    "babel-plugin-transform-react-jsx": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "jsx": "^0.9.89"
  }
}

这显然是我在我构建的库中的某个地方做错了;这是我第一次建立自己的图书馆,因此可能会犯错误。

标签: javascriptnode.jstypescriptnpmes6-modules

解决方案


推荐阅读