【问题标题】:'Cannot use import statement outside a module' followed by 'Uncaught TypeError: Failed to resolve module specifier'“不能在模块外使用导入语句”后跟“未捕获的类型错误:无法解析模块说明符”
【发布时间】:2020-11-26 22:13:45
【问题描述】:

我正在使用带有 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

package.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>

portis.jsthis CodeSandBox 相同。

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

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 上找到的大多数相关解决方案,但它似乎不起作用

【问题讨论】:

  • 尝试将 ... type="text/javascript" 放入您的脚本标签

标签: javascript node.js import


【解决方案1】:

检查portis.js 是否打包为ESM(包含export 子句),然后使用import Portis from './public/portis.js';

【讨论】:

  • 你能详细说明如何检查它是否被打包为 ESM 吗?它适用于该沙箱上的节点,我正在尝试复制它
  • 只检查里面是否有export 子句,它没有import 任何东西。顺便说一句,您所指的沙箱是一个前端,它具有使用 ParcelJS 的构建过程(而您似乎没有)
  • 我正在尝试在我的模板中使用 index.js(as portis.js),是的,我还没有实现 ParcelJS,有没有什么办法可以让你在没有 ParcelJS 的情况下获得源代码逻辑?跨度>
  • 完全不建议这样做。我想您正在尝试使用具有导入的文件?您应该使用构建过程来创建包含 portis 及其所有依赖项的包。捆绑工具还具有非常有趣的功能,例如摇树和缩小。作为替代方案,不要使用 ES 模块,并将 UMD 打包文件添加到您的 Web 应用程序(它会创建一个全局 Portis 对象)
  • 确实可以在 Node.js 或使用 Node.js 构建的浏览器应用程序中运行,但不能直接在浏览器中运行。
【解决方案2】:

将您的导入语句替换为

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

【讨论】:

  • Uncaught ReferenceError: require is not defined at portis.js:3 (anonymous) @ portis.js:3
猜你喜欢
  • 2021-05-19
  • 2020-05-18
  • 1970-01-01
  • 2020-03-11
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
相关资源
最近更新 更多