首页 > 解决方案 > “不能在模块外使用导入语句”后跟“未捕获的类型错误:无法解析模块说明符”

问题描述

我正在使用带 express 的节点服务器来使用Portis SDK。项目结构如下所示:

├── app.js (entry)
├── node_modules
├── package.json
├── package-lock.json
├── public (static files)
│   └── portis.js
└── views (templates and rendering)
    ├── home.html
    └── layouts

包.json

{
  "name": "src",
  "version": "1.0.0",
  "description": "YYYYY",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "XXXXX",
  "license": "ISC",
  "dependencies": {
    "@portis/web3": "^2.0.0-beta.59",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "express-handlebars": "^5.2.0",
    "pm2": "^4.5.0",
    "web3": "^1.3.0"
  },
  "devDependencies": {
    "@babel/core": "7.2.0",
    "@types/web3": "1.0.18",
    "parcel-bundler": "^1.6.1",
    "nodemon": "^2.0.6"
  }
}

在我的一个模板 ( home.html) 中,

<script src="/public/portis.js"></script>

并且与此 CodeSandBoxportis.js相同。

提供该模板时,出现错误:

Uncaught SyntaxError: Cannot use import statement outside a module (portis.js:1)

从搜索 SO 结果来解决它,当我更改home.html并将模块类型添加到脚本时:

<script type="module" src="/public/portis.js"></script>

(虽然type="module"没有在我复制的codesanbox中使用,但它可以完美运行)

但它会导致另一个错误:

Uncaught TypeError: Failed to resolve module specifier "@portis/web3". Relative references must start with either "/", "./", or "../".

(如果我删除import "@portis/web3",那么它会在下一个导入行给出相同的错误)

我已经尝试了我在 SO 上找到的大多数相关解决方案,但它似乎不起作用

标签: javascriptnode.jsimport

解决方案


将您的导入语句替换为

const Portis = require("@portis/web3");
const Web3 = require("web3");

推荐阅读