Understanding the difference between ‘require’ and ‘import’ in NodeJS
Hi, this is Charu from Games Solution Department, Classmethod. Recently I was working with TypeScript and I came up with 'require' keyword in place of 'import'. I have always used 'import' and seeing 'require' was new for me.
So, I searched on the internet and got to know the difference between the two. Hence, I am writing this short blog giving the difference between 'require' and 'import' thinking there might be others like me who are still unaware of these.
Let's get started!
Both of these keywords are used to import packages or modules in the Node.js project. But there are certain differences between them.
'require':
'require' is a module loading system commonly used in Node.js and older versions of JavaScript (ES5). It allows you to include external modules in your code.
Syntax:
var test = require('module_name')
Example:
const fs = require('fs');
In the example above, we use 'require' to import the Node.js 'fs' module, which provides file system-related functionality. This allows us to use the readFile method from the 'fs' module.
But, the few key points to notice about 'require' are,
'import':
With the introduction of ES6 (ECMAScript 2015), JavaScript gained built-in support for module loading using import and export. ES6 modules provide a more modern and flexible way to structure and load code.
Example:
import { DynamoDBClient} from "@aws-sdk/client-dynamodb";
In this example, we are importing only the dynamoDB client from aws-sdk/client-dynamodb module.
Few points to note about 'import' are,
Conclusion:
In TypeScript, both 'require' and 'import' can be used to include external modules in your code. The choice depends on the module system you are targeting, the TypeScript version, and your project's compatibility requirements. Understanding when to use each method will help you write more maintainable and type-safe code in your TypeScript projects.
Thank you for reading!
Happy Learning:)