Ad

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.

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad