gpt4 book ai didi

javascript - Node.js 无法导入 ES6 模块

转载 作者:行者123 更新时间:2023-12-05 08:14:29 26 4
gpt4 key购买 nike

我正在尝试将我的路由分离到一个单独的模块中 routes.js然后导入 app.js .我在控制台中遇到了很多错误。

internal/modules/esm/default_resolve.js:96
let url = moduleWrapResolve(specifier, parentURL);
^
Error: Cannot find module /Users/rhoxh/Desktop/24/routes imported from /Users/rhoxh/Desktop/24/app.js
at Loader.resolve [as _resolve] (internal/modules/esm/default_resolve.js:96:13)
at Loader.resolve (internal/modules/esm/loader.js:73:33)
at Loader.getModuleJob (internal/modules/esm/loader.js:147:40)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:41:40)
at link (internal/modules/esm/module_job.js:40:36) {
code: 'ERR_MODULE_NOT_FOUND'
}

路由.js

import express from 'express';

const router = express.Router();

router.get('/', (req, res) => {
res.send('home page');
});

export default router;

应用程序.js

import express from 'express';
import { router } from './routes';

const app = express();
const PORT = 8080;

app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});

// Routes
app.use('/', router);

我在这里做错了什么?

最佳答案

您需要使用完整的文件名:

import router from './routes.js';

来自documentation :

module-name

The module to import from. This is often a relative or absolute path name to the .js file containing the module. Certain bundlers may permit or require the use of the extension; check your environment. Only single quoted and double quoted Strings are allowed.

关于javascript - Node.js 无法导入 ES6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59913830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com