javascript - “不能在模块外使用导入语句”后跟“未捕获的类型错误:无法解析模块说明符”
问题描述
我正在使用带 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 上找到的大多数相关解决方案,但它似乎不起作用
解决方案
将您的导入语句替换为
const Portis = require("@portis/web3");
const Web3 = require("web3");
推荐阅读
- python - 酸洗动态创建的类
- emacs - 为什么emacs缩进包含'%'符号的字符串?
- anova - 来自单向方差分析测试的 F 值(不假设等方差)
- amazon-web-services - Terraform s3_bucket_policy
- android - 如何获取视图的android背景颜色
- c# - 未找到应用程序依赖项清单 (Microsoft.NETCore.App.deps.json) 中指定的程序集
- reactjs - 使用 NEXT.js 实现 Owl 轮播
- anaconda - Anaconda 环境错误 - 找不到 pythoncom38.dll 的过程入口点
- excel - 将公式从绝对转换为相对的问题。参考转移
- windows-subsystem-for-linux - WSL2 无法通过 Windows 访问,但可以通过终端正常工作