最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Error [ERR_MODULE_NOT_FOUND]: Cannot find module - Stack Overflow

programmeradmin5浏览0评论

I'm working on a node project (screenshot). I have a single function (urls) in helpers.js which I'm exporting at the bottom as:

module.exports = {
urls: urls,
};

In my index.js I'm trying to import it with:

import { urls } from './helpers';
const myUrls = urls(1,3);

When I run it I get

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/optionhomes11/nodeprojects/hayes/helpers' imported from /home/optionhomes11/nodeprojects/hayes/index.js Did you mean to import ../helpers.js?

What am I doing wrong?

I'm working on a node project (screenshot). I have a single function (urls) in helpers.js which I'm exporting at the bottom as:

module.exports = {
urls: urls,
};

In my index.js I'm trying to import it with:

import { urls } from './helpers';
const myUrls = urls(1,3);

When I run it I get

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/optionhomes11/nodeprojects/hayes/helpers' imported from /home/optionhomes11/nodeprojects/hayes/index.js Did you mean to import ../helpers.js?

What am I doing wrong?

Share Improve this question edited Sep 13, 2022 at 2:15 NiñoScript 4,5933 gold badges29 silver badges35 bronze badges asked Dec 20, 2020 at 21:02 user1592380user1592380 36.1k103 gold badges308 silver badges549 bronze badges 2
  • You're mixing node's CJS module system (require/module.exports) with ES6 modules (import/export). Don't do that unless you are very sure you know what you're doing, there are some gotchas both subtle and gross. – Jared Smith Commented Dec 21, 2020 at 15:43
  • 5 I miss the days when everything used to just work. The open source initiative was a good idea in theory, but nothing works properly anymore. Programming is way less fun than it used to be because of this type of completely unnecessary complexity. – bikeman868 Commented Jul 20, 2024 at 7:07
Add a comment  | 

14 Answers 14

Reset to default 212

When you are using ECMAScript modules you are forced to provide the file extension: https://nodejs.org/api/esm.html#esm_mandatory_file_extensions

So, on top of what other suggested of using "type": "module" on package.json you also need to specify the file extension import {urls} from './helpers.js'. You can also use the flag --es-module-specifier-resolution=node to make it resolve js files as modules just like it did before with require

This Happens because when using ES Modules we are enforced to specify the file extension in the import statement

import * from "./demo.js" // Works fine
import * from "./demo" // Will throw error as you see

Note that : The above two options are both valid when using commonJs instead

You have used

"type":"module"

then make sure you have import file must be .js extension

You're not doing anything wrong. The current resolution algorithm for EcmaScript Modules of file extensions and the ability to import directories that have an index file requires using an experimental flag. see esm, the bottom part.

so to make your work as it is, instead of

$ node index.js

you do:

$ node --experimental-specifier-resolution=node index.js

You can also create a script in your package.json

like so:

     "scripts": {
  "start": "NODE_OPTIONS='--experimental-specifier-resolution=node' node src/index.js

Try this as below

search in your "/home/optionhomes11/nodeprojects/hayes/index.js"

And looking for "/home/optionhomes11/nodeprojects/hayes/helpers"

change

"/home/optionhomes11/nodeprojects/hayes/helpers"

to

"/home/optionhomes11/nodeprojects/hayes/helpers.js"

//helpers.js

export default urls;

//index.js

import urls from './helpers.js';

//package.json (under name)

"type": "module"

You should be importing from './helpers', not '.helpers'.

Answer 1

This answer does not require using a runtime flag --es-module-specifier-resolution=node at execution time

However, you have to modify your ts source code, which is a pain if there is are a lot of files. And, the modified files will no longer compile in "commonjs" mode, if you want to go back or use dual "commonjs"/"module" modes.

Modify your tsconfig.json to ensure at least these setting versions:

   compilerOptions:{
    "lib": ["es2020"],
    "module": "ES2022",
    "moduleResolution": "node",
    "target": "es2022",
   }

Works with typescript 4.6.3. (Note sure about 4.6.1 or lower).*

Modify index.js

import {urls} from "#helpers";

Modify package.json

  "imports": {
    "#helpers": "./helpers.js"
  }

The leading "#" is mandatory

Answer 2

In addition to not requiring the node runtime execution flag, this answer also satisifes:

  1. does not require changing your *.*ts source code (thus leaving it compilable under commonjs if you ever chose to do so(*note))
  2. In case you are producing a library, it produces output which can be consumed by either "commonjs" or "module" clients.

(*note) When using rollup, inline maps are required - so there may sometimes be advantage to using commonjs during development and switching to "module" for release.

First modify package.json, create rollup.config.js, and then perform a post tsc action using rollup.

package.json

...
"exports":{
  "require":"./index.cjs",
  "import":"./index.js"
},
"types": "./index.d.ts",
"type": "module"    // you already had this

rollup.config.js

// import resolve from "@rollup/plugin-node-resolve";
import dts from "rollup-plugin-dts";
import commonjs from "@rollup/plugin-commonjs";
import * as path from "path";
import pkg from "./package.json";

export default [
  {
    input: "index.js",
    external:[], // you may quash 'unresolved' warning by adding here
    output: [
      { file: pkg.exports.require, format: "cjs" },
      { file: pkg.exports.import, format: "es" },
    ],
    plugins: [
      commonjs(),
    ],
  },
  {
    input: "./index.d.ts",
    output: [
      { file: pkg.types, format: "es" }, 
    ],
    plugins: [dts()],
  },
];

Call tsc then rollup:

npx tsc 
npx rollup -c

I would also recommend you install the Path Intellisense VS code extension. It will really help when handling nested paths.

I have faced this issue, I fixed it by adding dot(.) to the imported file import { connect } from "./dir/file.js";

instead of import { connect } from "./dir/file"; without the .js extention

use ".js" for all imports

If you're using any other js framework and experiencing the same or similar error to this one you can just delete the node_modules folder and do npm install. In many cases, that will fix the problem.

In my case some modifications made by my collogue (coder) to solve TooLarge error. I got this error when tried to git pull with the modifications. I tried many things but finally the below command worked for me.

npm install --legacy-peer-deps -f

//if you change package.json file, you should try to reload npm. Write this in terminal

npm i

发布评论

评论列表(0)

  1. 暂无评论