【问题标题】:Nodemon can't find module imports in same directory?Nodemon 在同一目录中找不到模块导入?
【发布时间】:2021-09-24 01:23:09
【问题描述】:

我有一个非常基本的 index.js,它有这样的导入:

import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import { Post } from "./entities/Post";

这是我的 package.json:

{
  "name": "reddit-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "watch": "tsc -w",
    "dev": "nodemon dist/index.js",
    "start": "node dist/index.js",
    "start2": "ts-node src/index.ts",
    "dev2": "nodemon --exec ts-node src/index.ts",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^16.3.2",
    "nodemon": "^2.0.12",
    "ts-node": "^10.1.0",
    "typescript": "^4.3.5"
  },
  "dependencies": {
    "@mikro-orm/cli": "^4.5.7",
    "@mikro-orm/core": "^4.5.7",
    "@mikro-orm/migrations": "^4.5.7",
    "@mikro-orm/postgresql": "^4.5.7",
    "pg": "^8.6.0"
  }
}

我用 tsc 将它们编译到 dist 目录中,其结构如下: [1]:https://i.stack.imgur.com/uC5pU.png

它给了我错误:

Cannot find module '/Users/kevinli/reddit-clone/reddit-server/dist/constants' imported from /Users/kevinli/reddit-clone/reddit-server/dist/index.js

我很困惑,因为它们似乎在同一个目录中并且应该正确导入?

如果我尝试删除 "type": "module",,它会告诉我无法导入模块外的内容。

【问题讨论】:

  • 你需要添加这个"type": "module"来告诉节点使用ES6导入。添加此配置时遇到什么错误?你是如何从常量模块中导出东西的?
  • 你能显示你的 tsconfig.json 文件的内容吗?
  • 另一个提示,在 node 中使用 ES6 模块时,将所有 js 文件重命名为“mjs”以进行区分。然后在导入和 package.json 的脚本和 main 中指定扩展名。对我来说,上次启用 ES6 模块时是必要的(使用节点 v14.15.3)

标签: node.js typescript nodemon


【解决方案1】:

我今天遇到了同样的问题。

尝试将扩展名.js 或其他任何内容添加到导入路径。 我了解到,没有扩展的 nodejs 假定路径是一个目录,因此它会在其中期待一个 index.js(默认)文件。

【讨论】:

    猜你喜欢
    • 2017-08-06
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多