Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'src'

Viewed 15320

Let's say my app looks like this

├── index.js
└── src
    ├── do_foo.js

do_foo.js

function foo() {
    return "bar";
}

export default foo;

index.js

import foo from 'src/do_foo';

foo();

Running node index.js results in the following error

> node index.js

internal/modules/run_main.js:54
    internalBinding('errors').triggerUncaughtException(
                              ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'src' imported from /mnt/c/Users/*******/Projects/*******/index.js
    at packageResolve (internal/modules/esm/resolve.js:620:9)
    at moduleResolve (internal/modules/esm/resolve.js:659:14)
    at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:752:11)
    at Loader.resolve (internal/modules/esm/loader.js:97:40)
    at Loader.getModuleJob (internal/modules/esm/loader.js:242:28)
    at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:50:40)
    at link (internal/modules/esm/module_job.js:49:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! fetch_courses@1.0.0 start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the *******@1.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /mnt/c/Users/*******/.npm/_logs/2020-07-21T03_38_34_404Z-debug.log

Seeing as I've managed to mess up at such an early point, the solution, I'd imagine, has to be pretty simple. What cardinal rule of javascript am I violating here?

I should add that I know everything will work if everything is in the same folder, but that's not what I'm aiming for. If at all possible, it's a better look to keep index.js in the outermost directory.

Edit: I want to clear up that my problem was NOT caused by a typo. My code was syntactically fine, it was the import that needed a relative scope. I mistyped something when I was writing the example code, that had nothing to do with the initial question.

3 Answers

You must use the full file path to get this working.

import foo from './src/do_foo.js';

console.log(foo());

Since its an experimental feature, you will get this warning.

ExperimentalWarning: The ESM module loader is experimental.

Yes, you are using typescript, in the tsconfig change "module":"esnext" for "module":"commonjs" and in the package.json "module":"commonjs".

This is is another way, albeit basic.

In your foo.js

You can run module.exports = foo;

In your index.js you can run

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port = 3000;

app.set('view engine', 'ejs');

app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));

const foo = require(__dirname + "/foo.js");

foo();
Related