After pulling down a module from GitHub and following the instructions to build it, I try pulling it into an existing project using:
> npm install ../faye
This appears to do the trick:
> npm list
/home/dave/src/server
└─┬ faye@0.7.1
├── cookiejar@1.3.0
├── hiredis@0.1.13
└── redis@0.7.1
But Node.js can’t find the module:
> node app.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Cannot find module 'faye'
at Function._resolveFilename (module.js:334:11)
at Function._load (module.js:279:25)
at Module.require (module.js:357:17)
at require (module.js:368:17)
at Object.<anonymous> (/home/dave/src/server/app.js:2:12)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
I really want to understand what is going on here, but I’m at a bit of a loss as to where to look next. Any suggestions?
asked Jan 26, 2012 at 18:57
8
Using npm install
installs the module into the current directory only (in a subdirectory called node_modules
). Is app.js located under home/dave/src/server/
? If not and you want to use the module from any directory, you need to install it globally using npm install -g
.
I usually install most packages locally so that they get checked in along with my project code.
Update (8/2019):
Nowadays you can use package-lock.json file, which is automatically generated when npm modifies your node_modules directory. Therefore you can leave out checking in packages, because the package-lock.json
tracks the exact versions of your node_modules, you’re currently using. To install packages from package-lock.json
instead of package.json
use the command npm ci
.
Update (3/2016):
I’ve received a lot of flak for my response, specifically that I check in the packages that my code depends on. A few days ago, somebody unpublished all of their packages (https://kodfabrik.com/journal/i-ve-just-liberated-my-modules) which broke React, Babel, and just about everything else. Hopefully it’s clear now that if you have production code, you can’t rely on NPM actually maintaining your dependencies for you.
answered Jan 26, 2012 at 19:15
BillBill
25k8 gold badges94 silver badges125 bronze badges
20
I had a very similar issue. Removing the entire node_modules
folder and re-installing worked for me:
rm -rf node_modules
npm install
answered May 25, 2015 at 10:30
Abhinav SinghAbhinav Singh
7,8421 gold badge23 silver badges33 bronze badges
5
npm install --save module_name
For example, if the error is:
{ [Error: Cannot find module ‘/root/.npm/form-data’] code: ‘MODULE_NOT_FOUND’ }
then you can resolve this issue by executing the command npm install --save form-data
.
bruntime
3712 silver badges13 bronze badges
answered Jun 17, 2015 at 8:51
Piyush ChordiaPiyush Chordia
1,3351 gold badge9 silver badges7 bronze badges
1
rm package-lock.json
rm -r node_modules
npm i
That should fix issue and install all packages.
answered Mar 26, 2021 at 11:53
XakiruXakiru
2,4981 gold badge15 silver badges11 bronze badges
0
For TypeScript users, if you are importing a built-in Node module (such as http
, path
or url
) and you are getting an error such as "Cannot find module "x"
then the error can be fixed by running
npm install @types/node --save-dev
The command will import the NodeJS TypeScript definitions into your project, allowing you to use Node’s built-in modules.
answered Oct 3, 2017 at 9:12
mgthomas99mgthomas99
5,1343 gold badges18 silver badges21 bronze badges
This happens when a first npm install has crashed for some reason (SIGINT of npm), or that the delay was too long, or data is corrupted.
Trying an npm install again won’t save the problem.
Something got wrong on the npm first check, so the best choice is to remove the file and to restart npm install.
answered Aug 6, 2015 at 16:23
Alex WernerAlex Werner
3603 silver badges9 bronze badges
1
I experienced this error yesterday. Took me a while to realise that the main
entry in package.json
was pointing to a file that I’d moved. Once I updated that the error disappeared and the package worked.
answered Aug 25, 2016 at 8:37
ukosteopathukosteopath
4337 silver badges14 bronze badges
4
Check if the enviroment variable NODE_PATH is set correctly and pointing to the node_modules path. nodejs uses this variable to search for the libraries
answered Feb 6, 2018 at 3:34
2
If you use nvm, check that existing node_modules that are bindings to other libraries are compiled for the correct Node.js version.
I was having the same error. The reason was the following: We use nvm since we’re running two apps on a server, one requires Node.js 5.6 because it uses node-gd (which doesn’t run on Node.js 6 for now), the other requires Node.js 6. Node.js 6 is the apt-get installation.
Also we use the pm2 tool to deploy.
So, the default setup is that the pm2 process starts when nvm is not in effect, so it uses the apt-get installation of Node.js (version 6). So the main pm2 daemon starts with Node.js 6. If I run applications in fork mode they start in separate processes and nvm settings are in effect. When I run applications in cluster mode — they inherit the non-nvm environment.
So when I tried to switch to the cluster mode the application failed to start because the bindings compiled for 5.6 fail with this message.
I’ve fixed that by restarting pm2 when nvm setings are in effect. Also startup scripts should be fixed.
answered Jun 10, 2016 at 11:30
0
This error can be encountered if you are require
ing a module that has a missing or incorrect main
field in its package.json. Though the module itself is installed, npm/node has to use a single .js file as an entrypoint to your module. If the main
field is not there, it defaults to looking for index.js
in your module’s folder. If your module’s main file is not called index.js, it won’t be able to require
it.
Discovered while turning a browserify
-based module into a CommonJS require
-able module; browserify
didn’t care about the missing main
field, and so the error had gone unnoticed.
answered Jun 23, 2017 at 14:30
MrCrankyMrCranky
1,48824 silver badges32 bronze badges
If all other methods are not working for you…
Try
npm link package_name
e.g
npm link webpack
npm link autoprefixer
e.t.c
answered Aug 10, 2020 at 17:07
James IkubiJames Ikubi
2,45025 silver badges17 bronze badges
2
Remove your node_module
root folder from your project(eg: myApp
).
Go to myApp
folder and then type below command from terminal
>myApp>npm install
It will install all the dependency modules required for your project.
answered Jul 6, 2016 at 7:25
1
PRO TIP:
This error happened to me, while fighting fatigue and mild illness, because I typed node blah
instead of npm blah
.
The error message received wasn’t angry enough to alert me to my own folly!
answered Sep 6, 2016 at 9:35
DaveDave
3,04334 silver badges32 bronze badges
Specify the path to the restler folder, which will be inside node_modules folder like : var rest = require(‘./node_modules/restler’);
This worked for me.
answered Sep 6, 2017 at 5:20
Just found an unusual scenario that may be of use to someone and is sort of a red herring.
I was also getting the Cannot Find Module error but oddly everything worked perfectly in my local (Mac hosted) Node.js environment. This problem only appeared when the code was deployed on our Linux server.
Well… it turned out to be a typo that (apparently) the Mac based Node.js installation was perfectly happy to ignore.
The include looked like this:
var S3Uploader = require('./S3Uploader.class');
But the actual file was called «s3Uploader.class.js»
Notice the casing difference in the ‘s’ vs. ‘S’ between the code and the filename.
So — in the odd chance that none of the other solutions here are solving your problem, triple check that you’re not mis-casing the characters in your included filename!
and DUH!
answered May 18, 2017 at 20:17
Yevgeny SimkinYevgeny Simkin
27.9k39 gold badges136 silver badges236 bronze badges
1
I can add one more place to check; the package that I was trying to use was another one of my own packages that I had published to a private NPM repo. I had forgotten to configure the ‘main’ property in the package.json properly. So, the package was there in the node_modules folder of the consuming package, but I was getting «cannot find module». Took me a few minutes to realise my blunder.
answered Jul 10, 2017 at 5:57
martinp999martinp999
4096 silver badges10 bronze badges
If you are using typescript and getting an error after installing all node modules then remove package-lock.json
. And then run npm install
.
answered Dec 20, 2019 at 6:22
Kartik GarasiaKartik Garasia
1,2841 gold badge17 silver badges27 bronze badges
- Run the following commands step by step. It fixed my issue:
npm cache clean –force
rm package-lock.json
rm -r node_modules
npm i —save —legacy-peer-deps
answered Sep 21, 2022 at 10:09
YasirYasir
4394 silver badges11 bronze badges
0
In my case I had UNMET PEER DEPENDENCY redux@^3.0.0
causing this error message, see all of them and install missing modules again using —save
npm install redux --save
answered Oct 18, 2017 at 11:50
I had this issue using live-server
(using the Fullstack React book):
I kept getting:
Error: Cannot find module './disable-browser-cache.js' ...
I had to tweak my package.json
-
From:
«scripts»: {
…
«server»: «live-server public —host=localhost —port=3000 —middleware=./disable-browser-cache.js»
…
}
«scripts»: { -
To:
…
«server»: «live-server public —host=localhost —port=3000 —middleware=../../disable-browser-cache.js»
…
}
Notice relative paths seem broken/awkward… ./
becomes ../../
I found the issue here
Also if anyone follows along with that book:
- change devDependencies in packages.json to:
"live-server": "https://github.com/tapio/live-server/tarball/master"
Currently that upgrades from v1.2.0 to v1.2.1
- It’s good to use nvm.
- It’s best to install v13.14 of Node (*v14+ creates other headaches)
nvm install v13.14.0
nvm alias default v13.14.0
- Update npm with
npm i -g npm@7.3.0
- run:
npm update
- you can use
npm list
to see the hierarchy of dependencies too. (For some reason node 15 + latest npm defaults to only showing first level of depth — a la package.json. That renders default command pointless! You can append--depth=n
) to make command more useful again). - you can use
npm audit
too. There issues requiring (update ofchokidar
and some others packages) to newer versions.live-server
hasn’t been updated to support the newer corresponding node v 14 library versions.
See similar post here
Footnote:
Another thing when you get to the JSX section, check out my answer here:
https://stackoverflow.com/a/65430910/495157
When you get to:
- Advanced Component Configuration with props, state, and children. P182+, node version 13 isn’t supported for some of the dependencies there.
- Will add findings for that later too.
answered Dec 21, 2020 at 20:42
JGFMKJGFMK
8,2954 gold badges55 silver badges92 bronze badges
0
In my case,
npm install -D tslib @types/node
solved my problem, I was then able to run
ts-node index.ts
successfully.
answered Jul 7, 2021 at 15:58
xpagesbeastxpagesbeast
7761 gold badge9 silver badges21 bronze badges
I was trying to publish my own package and then include it in another project. I had that issue because of how I’ve built the first module. Im using ES2015 export to create the module, e.g lets say the module looks like that:
export default function(who = 'world'){
return `Hello ${who}`;
}
After compiled with Babel and before been published:
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function () {
var who = arguments.length <= 0 || arguments[0] === undefined ? 'world' : arguments[0];
return 'Hello ' + who;
};
So after npm install module-name
in another project (none ES2015) i had to do
var hello = require('module-name').default;
To actually got the package imported.
Hope that helps!
answered Apr 6, 2016 at 7:53
BelgorBelgor
1811 gold badge2 silver badges9 bronze badges
Encountered this problem while using webpack
with webpack-dev-middleware
.
Had turned a single file into a folder.
The watcher seemed to not see the new folder and the module was now missing.
Fixed by restarting the process.
answered Apr 19, 2017 at 0:22
ChrisChris
2,7561 gold badge29 silver badges34 bronze badges
Maybe like me you set ‘view engine’ in express to an engine that doesn’t exist, or tried to use an unregistered templating engine.
Make sure that you use:
app.engine('engine name',engine)
app.set('view engine','engine name')
answered Feb 3, 2018 at 17:14
Removing node/npm and then re-installing the stable(not the latest) version worked for me.
sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}
https://nodejs.org/en/download/
answered Apr 12, 2019 at 15:50
KalKal
2114 silver badges15 bronze badges
In my case, i was not using the proper version of nvm.
answered Jul 28, 2021 at 5:51
maverickmaverick
822 silver badges14 bronze badges
A rare but also possible case is a typo in the module name. I missed the «s» in the file name when executing node .util.js
, where it should be node.utils.js
and didn’t find any solution among all the answers under this question until I found out that I can’t run the file even if I delete everything!
answered Sep 4, 2021 at 12:31
skygateskygate
3612 silver badges11 bronze badges
Apparently, judging by this question, there are a LOT of possible causes.
Maybe this will help someone, hoping nobody was as stupid as I was to use this technique:
Check if you have any node_modules folder up the folder tree.
Scenario 1:
If you ever had a projects folder, where you shared a node_modules folder between multiple projects, you may not have had any problems
|- projects
| |- node_modules <- OK
| |- project1 <- No node_modules folder
| | |- package.json
| |- project2 <- No node_modules folder
| | |- package.json
Scenario 2:
If you add a third project of a different nature, you may choose to keep a node_modules folder in that project:
|- projects
| |- node_modules <- Can be used by project 3
| |- project1 <- No node_modules folder
| | |- package.json
| |- project2 <- No node_modules folder
| | |- package.json
| |- project3
| | |- node_modules <- Packages for project 3 only
| | |- package.json
I’m guessing some packages in project 3’s node-modules folder are relying on packages that it finds (or doesn’t find) in the parent folder’s node_modules folder. Even though you’d expect the dependencies to be found in project 3’s node_modules folder. Maybe it’s because of the way some packages are imported and referenced?
Goes without saying that’s a disaster waiting to happen
answered Feb 16, 2022 at 19:14
DerpyNerdDerpyNerd
4,6887 gold badges39 silver badges91 bronze badges
I ran into this issue when I was upgrading the node version along with installing several different package versions. The project created a docker image/container to work in.
The issue was that the Docker image wasn’t recreated when I added a package and rebuilt the project. The proper information had been in my local package.json and package-lock.json files.
Deleting the Docker image and not just the container solved my problem.
answered Apr 29, 2022 at 14:11
majestzimmajestzim
5186 silver badges16 bronze badges
what ended up working for me was making sure to include any merge-deep dependencies as an external in your webpack config:
externals: {
puppeteer: 'require("puppeteer")',
}
And to declare the node_modules path relative to your package.json in your package.json as an ‘extraResource’.
"extraResources": [
"node_modules/puppeteer,
}
answered Dec 13, 2022 at 14:37
If you’re a developer that works with Node JS and JavaScript libraries and frameworks like React, Vue, and Angular, then you might have encountered the «Error: cannot find module» error.
In this article, I’m going to show you how to fix the error.
Why the «Error: cannot find module» Occurs
This error occurs because of the following reasons:
- you’re trying to import an item from a module you don’t have installed in your project directory
- you’re importing some things from an outdated package
- you’re pointing to a file that does not exist
In the screenshot below, you can see that I’m getting the error:
I’m getting the error because I’m trying to import the freeCodeCamp icon from the react-icons package, which I don’t have installed.
import { FaFreeCodeCamp } from "react-icons/fa";
How to Fix the «cannot find module» Error
If you get this error, the solution is always in the error. The module (package) not found is always specified in the format «Module not found: Error: Can’t resolve ‘package name’ in ‘project directory».
In my case, I got it like this «Module not found: Error: Can’t resolve ‘react-icons/fa’ in ‘C:UsersuserDesktopProjectsAddress Locatoraddress-locatorsrc'».
To fix the error, you need to install the package that is absent in your project directory – npm install package-name
or yarn add package-name
.
In my case, I need to install the react-icons
package so the freeCodeCamp icon can be resolved. I’ll do that by running yarn add react-icons
.
Once I install the package and run the app, everything should successfully compile:
If you install the package but you still get the error, then follow the steps below:
- delete the node modules folder by running
rm -rf node_modules
- delete package.lock.json file by running
rm -f package-lock.json
- clean up the NPM cache by running
npm cache clean --force
- install all packages again by running
npm install
That should fix the error for you.
Conclusion
When you get the “cannot find module” error, or “module not found”, it means you’ve not installed the package you’re trying to use.
If the error occurs even if you have the package installed, then the fixes suggested in this article can help you out.
Thank you for reading.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
When you are working in Node, you will sometimes encounter the error Cannot find module 'module-name'
with the error code MODULE_NOT_FOUND
.
The error looks like this:
internal/modules/cjs/loader.js:796
throw err;
^
Error: Cannot find module 'module'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
In this post, we’ll learn how to resolve this error.
What is the problem?
The issue is that Node is unable to find the module that you are trying to import into your Node application.
The most common reason for this is that you simply haven’t installed the project’s dependencies yet.
The project’s dependencies are listed in the package.json
file at the root of the project.
The Solution
To fix the Cannot find module
error, simply install the missing modules using npm
.
To so, you can use the following command:
npm install
If you are using the yarn
package manager, you can use the following command:
yarn install
This will install the project’s dependencies into your project so that you can use them.
Sometimes, this might still not resolve it for you. In this case, you’ll want to just delete your node_modules
folder and lock file (package-lock.json
or yarn.lock
) and try again.
This is how you can delete the node_modules
folder and lock files:
rm -rf node_modules
rm package-lock.json
rm yarn.lock
Local files
If your module is not coming from a remote source, you are seeing the error because the path to the local file is not correct.
Try to confirm that the path pointing to the local module is correct and your error should be resolved.
Conclusion
The Cannot find module
error is a common error that usually happens when dependencies are not installed. Once you install your dependencies and ensure that the paths are correct, you can resolve the error and run your application successfully.
Hopefully, this resolved the issue for you.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
-
Support Us
-
Join
-
Share
-
Tweet
-
Share
Give feedback on this page!
Sometimes, when developing a TypeScript project and importing a new package, you get a «cannot find module» error. Luckily, this error is easy to fix.
There are many reasons why the «cannot find module» error can happen in TypeScript:
- The package is not installed.
- Something is wrong with the node_modules folder.
- The package import contains a spelling mistake.
- Something is wrong with your tsconfig.json file.
This article will analyze those four potential causes and show how to fix this error for each one of them.
Let’s get to it 😎.
Page content
- Solution #1 — Install the package
- Solution #2 — Re-install your dependencies
- Solution #3 — Verify the import’s name
- Solution #4 — Fix the tsconfig.json file
- Final Thoughts
Here is how this error can look in your console:
bashCould not find a declaration file for module 'package/x'.
To fix this error, try those solutions one by one.
One of them will solve your error.
Solution #1 — Install the package
The first thing to fix the «cannot find module» error in TypeScript is to ensure that the package is installed on your system.
Run this command to install the package:
bashnpm install package-name
Also, some packages have a separate package with TypeScript types.
You need to install it as well, like so:
bashnpm install --save-dev @types/package-name
Solution #2 — Re-install your dependencies
Another potential fix for the «cannot find module» error is re-installing your dependencies. Indeed, something may be wrong with the project’s node_modules folder.
Here’s how to do it:
1. Remove the node_modules folder and the package-lock.json file, like so:
bashrm -rf node_modules package-lock.json
2. Install the dependencies like so:
bashnpm install
Solution #3 — Verify the import’s name
This error can occur when you try building your project on a different OS than originally built. Indeed, various case sensitivity errors can occur.
You must verify the import in question and match it to the file path.
If your file path is: path/File.ts
Your import should be the same: path/File.ts
It should NOT be: path/file.ts
Note: Set forceConsistentCasingInFileNames to true, inside the tsconfig.json file, for this not to happen.
Solution #4 — Fix the tsconfig.json file
Maybe this error occurs because something is wrong with the tsconfig.json file.
You can try to set the moduleResolution to node, like so:
json{
"compilerOptions": {
"moduleResolution": "node",
// Rest
}
}
If it doesn’t help, verify that your TypeScript file path is inside the include array AND is not inside the exclude array, like so:
json{
"include": ["src/**/*.ts", "tests/**/*.ts"],
"exclude": ["node_modules", ".vscode"],
// Rest
}
Or try adding a baseUrl, like so:
json{
"compilerOptions": {
"baseUrl": ".",
// Rest
}
}
Note: Sometimes, you must also add a valid paths entry for this solution to work.
Final Thoughts
As you can see, solving the «cannot find module» error in TypeScript is simple.
If it is a new dependency, it is usually a problem with the tsconfig.json file.
Otherwise, re-installing the dependencies will solve this error most of the time.
Here are some other TypeScript tutorials for you to enjoy:
- Define a singleton in TypeScript
- Export a function in TypeScript
- Use instanceOf on an interface in TypeScript
written by:
Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada.
I specialize in React, Node.js & TypeScript application development.
If you need help on a project, please reach out, and let’s work together.
Introduction
A common error that can come up when working with Node applications is the error of:
ERR_MODULE_NOT_FOUND]: Cannot find module
This generally means that whatever module you are trying to import is not being found.
A more descriptive error from the terminal looks like the below:
> node dist/app.js
node:internal/errors:465
ErrorCaptureStackTrace(err);
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'redacted/dist/config/datadog' imported from /redacted/dist/app.js
at new NodeError (node:internal/errors:372:5)
at finalizeResolution (node:internal/modules/esm/resolve:405:11)
at moduleResolve (node:internal/modules/esm/resolve:966:10)
at defaultResolve (node:internal/modules/esm/resolve:1176:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:605:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:318:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:80:40)
at link (node:internal/modules/esm/module_job:78:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
Node.js v18.0.0
Process finished with exit code 1
So in the above error message, our app.js is importing the datadog
module. The erro comes up because the app.js code cannot find the datadog
module.
To fix this error, there are few things we can do:
- Check that you are using the
import
/export
syntax correctly - Make sure to have the file extension
.js
when you import - Make sure that the module exists and you have supplied the correct path.
- You are not mixing and matching with CommonJs — eg using the
require()
function
1. Check that you are using the import
/ export
syntax correctly
Firstly, if we want to make sure that we do not get this error, check that we are using the import and export syntax correctly.
As an example, lets say you have a file called helloModule.js which exports a function:
export function sayHello() {
console.log("Hello World!");
}
You can then import this function into another file — app.js using the import statement:
import { sayHello } from './helloModule.js';
sayHello(); // Output: Hello World!
In the above example, we are importing the helloModule.js to be used in our app.js file — the sayHello()
function.
Node will consider a file as ECMAScript modules when it satisfies the following:
- Files ending in .js if there is a top-level field “type” with a value of “module” in the nearest parent package.json file
- Files ending in .mjs
- Strings passed in as an argument to –eval or –print, or piped to node via STDIN, with the flag –input-type=module.
2. Make sure to have the file extension .js
when you import
One thing to keep in mind when doing import
is that the file MUST have an extension.
As specified in the Node docs — it is mandatory to have file extensions when working with import
keyword (https://nodejs.org/api/esm.html#mandatory-file-extensions)
Consider the following code:
import { sayHello } from './helloModule'; ❌ /* Will give you error - need .js extension */
import { sayHello } from './helloModule.js'; ✔️ /* This will work!*/
The first import will not work and will give you “ERR_MODULE_NOT_FOUND” since there is no extension (.js)
Note: The behavior tries to match how import behaves in browser environments
In the browser, imports still require file extensions (eg .js), but we can get around it using bundlers/ transpilers such as Webpack!
3. Make sure that the module exists and you have supplied the correct path.
One thing to keep in mind is that you are providing the correct path.
.
└── My project/
├── node_modules
├── common/
│ └── helloModule.js
├── app.js
├── db/
│ └── index.js
└── package.json
Now if we want to use helloModule.js in our app.js file, we have to make sure that the path is correct.
import { sayHello } from './helloModule.js'; ❌ /* Will give you error - wrong path */
import { sayHello } from './common/helloModule.js'; ✔️ /* This will work!*/
In the above, our helloModule.js is in the common
folder and we need to specify it relative to app.js
4. Check that not mixing and matching with CommonJs — eg using the require()
function
As specified in the Node docs (https://nodejs.org/api/esm.html) — Node comes with two module systems.
The old way to import javascript libraries or common code is to use CommonJS.
This uses the require()
function to load libraries that you want to use with your code.
Since Node version 14, ESM modules are introduced — which lets us use the import
/ export
keywords.
You should NOT mix and match ES6 modules and CommonJS syntax together!
You can only pick one module system — for example the below code will not work:
❌ /* will not work since mixing and matching require and import */
const { sayHello } = require('./helloModule.js');
import { sayHello } from './common/helloModule.js';
Convert to use ESM modules
If you already have require() methods to load your JS files and want to use the new ES6 module syntax with import
and export
, we can do the following:
- Replace
require()
, with theimport
keyword.
So instead of doing this:
const express = require('express');
We can convert to the new ES6 syntax with import/export.
(Note: keep in mind that you still have the “type” value as “module”)
import express from 'express';
- In the package.json, make sure the “type” attribute is “module”.
For example:
{
"name": "TestApp",
"main": "server.js",
"type": "module", ✔️
...
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"chalk": "^4.0.0",
"dotenv": "^8.2.0",
"express": "^4.17.1"
},
"devDependencies": {
"sequelize-cli": "^5.5.1"
}
}
Convert to use CommonJS
The other option is to revert and keep using CommonJS.
To this this issue, we can do the following:
- Change the “type” value from “module” to “commonjs”
- Change all
import
torequire()
import express from 'express';
Becomes
const express = require('express');