我在节点js中使用“type”:“module”时遇到错误

问题描述 投票:0回答:1

我是nodejs新手。 我用expressjs在Cpanel中制作了简单的节点应用程序:

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”的情况下工作

在本地,两个版本都可以正常工作。我读到将来最好使用“导入”而不是“要求”。 有什么问题吗

node.js express import module cpanel
1个回答
0
投票

看起来 CPanel 使用的 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)

© www.soinside.com 2019 - 2024. All rights reserved.