import和const之间有什么区别,哪个在commonjs中是首选

时间:2022-03-19 13:33:46

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

我注意到使用const和import在使用带有Babel的es6语法的node.js应用程序中引用库之间进行了一些切换。

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和import有什么区别?假设您可能在许多文件/组件中导入相同的库。

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.

import语句用于导入从外部模块,另一个脚本等导出的函数,对象或基元。

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.

const声明创建对值的只读引用。它并不意味着它拥有的值是不可变的,只是无法重新分配变量标识符。

1 个解决方案

#1


9  

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

什么是首选方法,使用const和import有什么区别?

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

在2016年,坚持导入是有道理的,因为这是标准的一部分。

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.

没有技术上的理由更喜欢导入而不是需要:可以使用require完成的所有操作都可以通过import完成,反之亦然。在某些情况下,一个会更简洁,另一个则更简洁。

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

总结:选择符合项目代码约定/一致性的那个。

#1


9  

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

什么是首选方法,使用const和import有什么区别?

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

在2016年,坚持导入是有道理的,因为这是标准的一部分。

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.

没有技术上的理由更喜欢导入而不是需要:可以使用require完成的所有操作都可以通过import完成,反之亦然。在某些情况下,一个会更简洁,另一个则更简洁。

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

总结:选择符合项目代码约定/一致性的那个。