[英]Why I'm getting Error [ERR_MODULE_NOT_FOUND]: Cannot find module when running the server
I'm doing a startup server.我正在做一个启动服务器。 Basically It has initial setup with express and nodemon dependencies.
基本上它具有 express 和 nodemon 依赖项的初始设置。 Unfortunately, I'm getting
ERR_MODULE_NOT_FOUND
when running yarn dev
or npm run dev
Here is the code and file structure I have.不幸的是,我在运行
yarn dev
或npm run dev
时得到ERR_MODULE_NOT_FOUND
这是我拥有的代码和文件结构。
You need to add.js extension index.js:您需要添加.js 扩展名 index.js:
import { SampleExport } from "../path/file.js"
In my opinion, it is better to use.env files together with some npm package or even a json file.在我看来,最好将 .env 文件与一些 npm package 甚至 json 文件一起使用。
Nodemon is developer dependency you need to do these commands: Nodemon 是开发人员依赖项,您需要执行以下命令:
npm uninstall --save nodemon
npm install --save-dev nodemon
Instead of using export itself you should use module.exports = someFuncName
in your env.js
file.您应该在
env.js
文件中使用module.exports = someFuncName
而不是使用 export 本身。 export not working and js can not require your function or something...导出不起作用,js 不能要求您的 function 或其他东西...
The issue is a missing file extension.问题是缺少文件扩展名。 The import needs to look like this:
导入需要如下所示:
import { sampleExport } from "../config/env.js";
// ^^^
import
doesn't use the same algorithm that require
used. import
不使用require
使用的相同算法。 Instead, it works according to the ECMAScript Modules specification, which requires a definite extension.相反,它根据 ECMAScript 模块规范工作,该规范需要明确的扩展。
This is also explained in the node.js docs for ECMAScript modules :这也在ECMAScript 模块的 node.js 文档中进行了解释:
A file extension must be provided when using the
import
keyword to resolve relative or absolute specifiers.使用
import
关键字解析相对或绝对说明符时,必须提供文件扩展名。 Directory indexes (eg'./startup/index.js'
) must also be fully specified.还必须完全指定目录索引(例如
'./startup/index.js'
)。This behavior matches how
import
behaves in browser environments, assuming a typically configured server.此行为与
import
在浏览器环境中的行为方式相匹配,假设是典型配置的服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.