簡體   English   中英

“不能在模塊外使用導入語句”后跟“未捕獲的類型錯誤:無法解析模塊說明符”

[英]'Cannot use import statement outside a module' followed by 'Uncaught TypeError: Failed to resolve module specifier'

我正在使用帶 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.js此 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"沒有在我從中復制的代碼框中使用,並且它可以完美地運行)

但它會導致另一個錯誤:

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

(如果我刪除import "@portis/web3"那么它會在下一個導入行給出相同的錯誤)

我已經嘗試了我在 SO 上找到的大多數相關解決方案,但它似乎不起作用

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

將您的導入語句替換為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM