DEV Community

Cover image for Lessons from open-source: Can you use "require" and "import" in the same file in NodeJs
Ramu Narasinga
Ramu Narasinga

Posted on • Edited on

Lessons from open-source: Can you use "require" and "import" in the same file in NodeJs

This lesson is picked from next.js/packages/next. In this article, you will learn how Next.js uses require and import in the same file.

require import example

I found it fascinating that "require" is used in the code, not at the top. We all usually do the import/require at the top of file.

Practice the exercises based on documentation to become an expert in Next.js

Here are the imports from top of the file as shown below

imports

Can you just mixup "import" and "require"?

I tried to set up a simple nodejs project on codesandbox with import and require mixed up. Because it's good, you usually don't see imports done in the middle of a file.

It's good. So good, it scratched that part of my mind. The part that doesn't allow good to exist without a condition. - Elliot (Mr.Robot)

Some of the issues I faced:

1. Type: Module

(node:5176) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/workspaces/sandbox/src/index.js:1
import { logger } from "./utils";
^^^^^
Enter fullscreen mode Exit fullscreen mode

Codesandbox

Right, does adding "type": "module" in package.json fix it?

2. require is not defined in ES module scope

More errors, I like it, except this time it is a different error, this was fun. 

I did some research and but I found my answers in next.js source code

Webpack to the rescue

I found that next main points to "./dist/server/next.js". hmm, dist? right, this is where it occured to me that I should be looking for bundlers used and I found the webpack.config.js

I immediately installed webpack and put my files inside src folder and did npx webpack and I have dist/main.js which I changed in my package.json

compiled successfully

with that, I was able to compile and see my experimental logs appear.

Conclusion:

Because I have never seen the usage of "require" and "import" in the same file, it was so good I had to set up a codesandbox to run these experiments and documented them in this article. 

It was so good, it scratched that part of my mind. The part that connects the dots and finds answers.

Get free courses inspired by the best practices used in open source.

About me:

Website: https://ramunarasinga.com/

Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/

Github: https://github.com/Ramu-Narasinga

Email: ramu.narasinga@gmail.com

Learn the best practices used in open source.

Top comments (0)