Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between import and const and which is preferred in commonjs

I have noticed a bit of switching between using const and import for referencing libraries in node.js applications using es6 syntax with Babel.

What is the preferred method and what is the difference between using const and import? Assuming you may be importing the same library in many files/components.

const

const React = require('react') 

import

import React from 'react' 

Here are the definitions of each but I am still not sure which to use.

import

The import statement is used to import functions, objects or primitives that have been exported from an external module, another script, etc.

const

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned.

like image 571
svnm Avatar asked Jan 04 '16 23:01

svnm


People also ask

Can I use import with CommonJS?

If "type": "commonjs" , then an ES module is any . mjs file. You can only use import and export in an ES module. Specifically, this means you can only use import and export in a .

Is import supported in Nodejs?

Node js doesn't support ES6 import directly. If we try to use import for importing modules directly in node js it will throw out the error. For example, if we try to import express module by writing import express from 'express' node js will throw an error as follows: Node has experimental support for ES modules.

How are ES modules different from CommonJS modules?

ES modules are the standard for JavaScript, while CommonJS is the default in Node. js. The ES module format was created to standardize the JavaScript module system. It has become the standard format for encapsulating JavaScript code for reuse.

What is a CommonJS module?

Getting Started. From a structure perspective, a CommonJS module is a reusable piece of JavaScript that exports specific objects made available to any dependent code. Unlike AMD, there are typically no function wrappers around such modules (so we won't see define here, for example).


1 Answers

What is the preferred method and what is the difference between using const and import?

In 2016 it makes sense to stick with the import since that's the part of the standard.

There is no technical reason to prefer import over require though: everything that can be done using require can be done with import and vice versa. In some cases one will be more concise, in another - the other.

To summarise: choose the one that fits the project code conventions/consistency.

like image 167
zerkms Avatar answered Sep 23 '22 08:09

zerkms