首页 > 解决方案 > Javascript 导入/导出语句

问题描述

在 javascript 中,它们是否都相似(第 1 部分和第 2 部分)?

[第1部分]

const sething = () => {
  //Something
}

const sething1 = () => {
  //Something 
}

[第2部分]

const sething = () => {
  //Something 
}

export default sething

进而

import sething from /location 

const sething1 = () => {
  //Something 
}

如果它们都不相似,有人可以告诉我为什么不相似吗?并建议阅读任何文章。

另外,如果我们为类做这样的事情,结果会怎样?

标签: javascript

解决方案


我认为您在问:“第 1 部分是否等同于第 2 部分”,其中第 2 部分sething在单独的文件中定义,然后将其导入到与sething1.

我的回答是:

  • 有一些方法是等价的
  • 有一些方法是不同的

它们如何等效?

In both Part 1 and Part 2, you end up with sething and sething1 defined as constants. If all you're concerned about is the behaviour of your application then for the most part I'd treat these as equivalent.

How are they different?

  1. If you re-use sething somewhere else, you'll simple be able to import it there. You can do that in Part 2 but not without refactoring or repeating yourself in Part 1. Or perhaps having one massive file.
  2. If you wish to refactor the name sething, it'll be easier in Part 1 than in Part 2. In Part 2 most IDEs will change the imported name without changing the name of the constant inside the imported file. If it's used anywhere else, those uses will not be renamed. This can easily be fixed by using a named export instead of a default export.

I hope that helps and answers your question!


推荐阅读