我在node js中使用“type”:“module”时出错

0g0grzrc  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(272)

我是nodejs的新手。我用expressjs在Cpanel中做了一个简单的node应用:

import express from 'express';
const app = express();
const port = '';

app.get('/', (req, res) => {
  res.send('Hello World!');
})

app.get('/about', (req, res) => {
  res.send('Hello about!');
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
})

我的package.js是这样的。

{
"name": "myapp",
"version": "1.0.0",
"description": "App",
"main": "index.js",
"scripts": {
    "test": "test"
},
"author": "Name Surname",
"license": "MIT",
"dependencies": {
    "express": "^4.17.1"
},
"type":"module"

}
但我犯了个错误

App 3183657 output: /opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:80
App 3183657 output:     return originalRequire.apply(this, arguments);
App 3183657 output:                         ^
App 3183657 output: Error [ERR_REQUIRE_ESM]: require() of ES Module /home/makyansystems/public_html/simple.makyan.online/index.js from /opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js not supported.
App 3183657 output: Instead change the require of index.js in /opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js to a dynamic import() which is available in all CommonJS modules.
App 3183657 output:     at Module.require (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:80:25)
App 3183657 output:     at loadApplication (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:243:2)
App 3183657 output:     at setupEnvironment (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:214:2)
App 3183657 output:     at Object.<anonymous> (/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js:133:1) {
App 3183657 output:   code: 'ERR_REQUIRE_ESM'
App 3183657 output: }
App 3183657 output: Node.js v20.3.1

但不使用“type”:“module”或使用“type”:“commonJS”也可以工作
在本地工程罚款两个版本。我读到,在未来的好用“进口”,而不是“要求”。有什么问题吗?

n3schb8v

n3schb8v1#

看起来像JS脚本(你可以在错误消息中看到它:/opt/cpanel/ea-ruby27/root/usr/share/passenger/helper-scripts/node-loader.js)使用require(...)导入您的代码,因此希望您的脚本是CommonJS模块,而不是ES模块。
因此,您必须在代码中使用require而不是import。或者,您可以使用动态import()https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import

相关问题