发布于 2026-01-06 3 阅读
0

Import and Export Statements in JavaScript and How to Use Them

JavaScript 中的导入和导出语句及其使用方法

import 和 export 语句是 ES6(ES2015)引入的两项重要特性。这两项语句允许您导出和导入代码,并在需要时随时使用。本教程将向您展示 import 和 export 语句的概念、工作原理以及使用方法。

简要介绍

过去,当 JavaScript 开发者想要将代码拆分成模块时,他们只能选择AMDCommonJSUMD这三种方案之一。JavaScript本身就内置了对模块的支持。但 ES2015(ES6)规范的发布改变了这一切。

该规范为 JavaScript 带来的一项特性是语言层面的模块支持。JavaScript 开发者现在能够借助新引入的 import 和 export 语句来使用原生模块。现在,作为一名 JavaScript 开发者,您可以将代码拆分成多个文件。

这些文件都是一个模块。这些模块可以包含任何内容,从变量和函数到类。要让这些代码可供外部使用,只需将其导出即可。当需要使用已导出的代码时,只需在需要的地方导入即可。现在,让我们来看看这两个新语句。

出口声明

当你想导出某个变量、函数或类时,必须export在它们前面加上 `export` 关键字。这会告诉 JavaScript 两件事。首先,你希望这个“东西”可以从当前文件外部访问。其次,程序的其他部分应该能够使用 `import`import语句导入这个“东西”。

导出代码后,您仍然可以对其进行修改和更新。但是,您只能在导出代码的位置进行这些操作。将导出的代码导入到其他位置后,您无法再进行修改。导入导出的代码后,您只能读取和使用,而不能对其进行修改。

两种导出方式

当你想用export语句导出代码时,有两种方法。第一种方法是在声明时就进行导出。在这种情况下,你export需要将导出语句放在同一行,紧挨着你要声明的变量、函数或类。

// Declare and export variables
export const MY_PASS = 'Some very important secret.'
export let name = 'Jack'
export var stack = 'JS'

// Declare and export functions
export function sayHi() {
  return 'Hi.'
}

export const sayBye = function() {
  return 'Bye.'
}

export const sayGoodBye = () => {
  return 'Good bye.'
}

// Declare and export class
export class Person {
  name = this.name
  age = this.age
  #my_secret = this.secret
}
Enter fullscreen mode Exit fullscreen mode

导出代码的第二种方法是先声明代码,然后再导出。在这种情况下,你export需要使用 `export` 语句,后跟要导出的“内容”。

// Declare variables
const MY_PASS = 'Some very important secret.'
let name = 'Jack'
var stack = 'JS'

// Export variables
export MY_PASS
export name
export stack

// Declare functions
function sayHi() {
  return 'Hi.'
}

const sayBye = function() {
  return 'Bye.'
}

const sayGoodBye = () => {
  return 'Good bye.'
}

// Declare and export functions
export sayHi
export sayBye
export sayGoodBye

// Declare class
class Person {
  name = this.name
  age = this.age
  #my_secret = this.secret
}

// Export class
export Person
Enter fullscreen mode Exit fullscreen mode

如果您决定使用第二种方法,还需要注意一点。您不必逐个导出所有内容,而是可以使用一条export语句一次性导出。例如,在文件末尾添加一条语句。为此,您需要将所有要导出的内容用花括号括起来,并用逗号分隔。

// Declare some stuff
const MY_PASS = 'Some very important secret.'

let name = 'Jack'

function sayHi() {
  return 'Hi.'
}

class Car {
  numOfWheels = this.numOfWheels
  typeOfFuel = this.typeOfFuel
}

// Export all the stuff at once
export { MY_PASS, sayHi, Car }
Enter fullscreen mode Exit fullscreen mode

命名和默认导出

您还可以使用两种类型的导出:命名导出和默认导出。对于命名导出,您可以创建任意数量的导出项,没有数量限制。但默认导出则不然。在 JavaScript 中,每个模块只能有一个默认导出项。

第一种类型,名为 export,就是您在上面的示例中看到的。在这些示例中,您使用了export关键字以及要导出的内容的名称。所有这些导出操作都使用了名称。如果您想导出某个内容,default则需要在语句和要导出的内容default之间添加名称。export

// Named export
export const LANG = 'English'

// or
const favoriteFantasy = 'Discworld'
export favoriteFantasy


// Default export
export default const LANG = 'English'

// or
const favoriteFantasy = 'Discworld'
export default favoriteFantasy
Enter fullscreen mode Exit fullscreen mode

还有另一种导出方式default。你可以用花括号将要导出的内容名称括起来。然后,添加as关键字 `export`,再添加default关键字 `default`。这样也会将该文件导出为默认文件。

// Another way to create default export
const FAVORITE_SEASON = 'Summer'

// Export FAVORITE_SEASON as default
export { FAVORITE_SEASON as default }
Enter fullscreen mode Exit fullscreen mode

重命名导出

当你导出某个内容,并且不想使用变量、函数或类名时,可以对其进行重命名。为此,你需要用花括号将原名称括起来,并as在后面加上关键字,再写上你想要使用的新名称。如果你要导出多个内容,可以使用此方法重命名所有内容,也可以只重命名部分内容。

// Declare a variable
let sillyJoke = 'Knock, knock.'

// Export the variable and rename it
export { sillyJoke as classicJoke }


// Declare multiple variables
const petOne = 'Dog'
const petTwo = 'Cat'
const petThree = 'Alligator'
const petFour = 'Dragon'

// Export all variables and rename some
// Note: line breaks are just for readability
export {
  petOne,
  petTwo as pet2, // rename export for petTwo
  petThree as pet3, // rename export for petThree
  petFour
}
Enter fullscreen mode Exit fullscreen mode

再出口出口

最后,你可以使用export语句导入一些文件,然后立即再次导出。在此过程中,你可以保留它们的名称,也可以重命名。重新导出的语法与导入的语法类似,稍后你会学到相关内容。

如果需要重新导出,首先要写出 `export`export语句。后面是花括号,括号内是要导出的模块名称。再后面是from关键字 `export` 和导出该模块的文件名。如果要重命名导出的模块,请as在花括号内的模块名称后添加关键字 `export` 和新名称。

// Re-export module
export { myExpModule } from './file.js'

// Re-export module and rename it
export { myExpModule as myRenamedExpModule } from './file.js'
Enter fullscreen mode Exit fullscreen mode

当您想要重新导出默认导出时,也使用相同的语法。在这种情况下,花括号内应填写“default”而不是模块名称。或者,您可以将其替换为其他内容*并省略花括号。

// Re-export default module
export { default } from './file.js'

// Alternative
export * from './file.js'

// Re-export default module and rename it
export { default as defaultRenamed } from './file.js'
Enter fullscreen mode Exit fullscreen mode

进口声明

当你想导入一些代码时,必须使用 `import`import语句。请记住,这仅适用于你使用 `import`export语句导出的代码。你无法导入未导出的代码。导入时,有两种方法可供选择。我们稍后会详细介绍。

两种情况下,都必须以关键字开头import。接下来,指定要导入的导出模块的名称。这部分语法会根据您选择的选项而有所不同。之后是from关键字,再后跟要从中导入模块的文件名。

// Example of import syntax
import { someModule } from 'file.js'
import someModule from 'file.js'
Enter fullscreen mode Exit fullscreen mode

命名导入

第一种方法是逐个导入模块,也就是您之前导出的内容。如果您选择这种方法,则需要考虑您导出这些模块的方式。如果您使用命名导出功能导出这些模块,则必须使用与导出时完全相同的名称。如果您使用了重命名功能,则必须使用重命名后的名称。

导入命名导出时,必须用花括号将名称括起来。这是导入命名导出时的必要步骤。与导出类似,您也可以使用多条import语句分别导入所有导出项,或者使用单条语句导入所有导出项import。在这种情况下,必须用逗号分隔各个导出的模块。

// File 1: file-one.js
// Declare and export some stuff
// Use named export
export const age = 29

function sayHi() {
  return 'Hello'
}

// Use named export with renaming
export { sayHi as greeting }


// File 2: file-two.js
// Import only the "age" variable
import { age } from './file-one.js'

// Try to read imported "age" variable
console.log(age)
// Output:
// 29


// Import only the "greeting" function
// Note: you exported the sayHi as greeting
// so you have to import it as greeting, not as sayHi
import { age } from './file-one.js'

// Import both, "age" and "greeting"
import { age, greeting } from './file-one.js'

// Try to read imported "age" variable
console.log(age)
// Output:
// 29

// Try to call imported "greeting" function
console.log(greeting())
// Output:
// 'Hello'
Enter fullscreen mode Exit fullscreen mode

默认导入

如果你导出了某个模块default,你可以随意选择导入该模块的名称。但是,如果要导入默认导出的模块,请不要用花括号将模块名称括起来。否则,JavaScript 会抛出错误。还有一点很重要:当你使用默认方式导入某个模块时,不要使用变量关键字。

// File 1: file-one.js
// Declare and export some stuff as default
// Note: omit the "const", "let" or "var" keywords
export default surname = 'Joe'


// File 2: file-two.js
// Import only default export "name"
// Note: no curly braces around the name
import surname from './file-one.js'

// Try to read imported "age" variable
console.log(surname)
// Output:
// 'Joe'
Enter fullscreen mode Exit fullscreen mode

当您将某个内容导出为默认导出时,无需在其他地方使用相同的名称来导入它。使用默认导出时,JavaScript 会知道该文件只包含一个导出项。因此,即使您使用不同的名称来导入该内容,它也能确定您要导入的内容。

// File 1: file-one.js
// Declare and export some variable as default
export default secret = 'This is some very important secret.'


// File 2: file-two.js
// Import the default export using a different name
import password from './file-one.js'

// Try to read imported "age" variable
console.log(password)
// Output:
// This is some very important secret.
Enter fullscreen mode Exit fullscreen mode

一次性导入指定名称的模块

第二种方法是一次性导入所有内容。请记住,这将导入您从当前要导入的文件导出的所有内容。语法与导入单个模块类似,区别在于两点。首先,您需要将要导入的模块名称替换为*星号 (*)。

其次,您需要添加as关键字,后跟您希望访问这些导入模块的名称。这个名称可以随意命名。

// File 1: file-one.js
// Declare and export some stuff
export const pets = ['Dog', 'Shark', 'Tiger']
export const currentlyReading = 'Snow Crash'
export function add(a, b) {
  return a + b
}


// File 2: file-two.js
// Import everything exported from file-one.js
import * as myStuff from './file-one.js'

// Try to read the value of imported "pets" variable
console.log(myStuff.pets)
// Output:
// ["Dog", "Shark", "Tiger"]

// Try to read the value of imported "currentlyReading" variable
console.log(myStuff.currentlyReading)
// Output:
// "Snow Crash"

// Try to call the imported add() function
console.log(myStuff.add(89, 98))
// Output:
// 187
Enter fullscreen mode Exit fullscreen mode

重命名导入项

与 `import` 语句类似exportimport`rename` 语句也允许您重命名导入项。当您想要导入某个模块,但希望使用不同的名称时,此功能非常有用。其语法与重命名导出项的语法类似。唯一的区别在于,您需要将 `import`export语句替换为 ` rename` import

// File 1: file-one.js
// Declare and export some stuff
export const transpiler = 'Babel'
export const language = 'JavaScript'
export const syntax = 'jsx'
export const framework = 'React'


// File 2: file-two.js
// Import modules exported from file-one.js
// and rename some of those imports
// Note: line breaks are again just for readability
import {
  transpiler,
  language,
  syntax as fileExtension,  // rename export for syntax
  framework as library  // rename export for framework
} from './file-one.js'

// Try to read the value of imported "pets" variable
console.log(syntax)
// Output:
// "jsx"

// Try to read the value of imported "currentlyReading" variable
console.log(library  )
// Output:
// "React"
Enter fullscreen mode Exit fullscreen mode

导入单个命名导出和默认导出

语句的一个优点import是它可以同时处理命名导出和默认导出。因此,如果您在同一个文件中同时使用了命名导出和默认导出,您仍然可以使用单个import语句分别导入这些模块。要做到这一点,您需要记住两点。

首先,导入所有默认导出项时,无需用花括号将其括起来。其次,导入所有剩余的命名导出项时,必须使用花括号将其括起来。如果导入两个或多个命名导出项,请用逗号分隔它们。务必将它们全部放在同一个花括号内。

// File 1: file-one.js
// Declare and export some stuff
export default tvShow = 'Breaking Bad'
export const mainCharacter = 'Walter White'
export const subject = 'Chemistry'
export const rating = '9.5/10'


// File 2: file-two.js
// Import both named and default exports from file-one.js
// Note: the default export "tvShow" has to be first
// and outside of the curly braces
import tvShow, { mainCharacter, subject, rating } from './file-one.js'
Enter fullscreen mode Exit fullscreen mode

动态导入

Now you know about import and export statements and how to use them. However, the import statement is not the only way to import modules. There is also an alternative called dynamic import. The main difference between the import statement and dynamic import is that the import statement is static.

This means that when you import something with import statement it will be imported at the moment you run your code. If you import some large module, or a lot of them, it can make your code slower. Dynamic import works differently. Dynamic imports are not loaded at the moment you run your code.

Well, they can, but only if you want that to happen. If not, you can delay their load. You can use dynamic imports also to load things only under certain condition. If this condition never happens that dynamic import will not be loaded. In that case, that additional module will logically have no effect on the performance of your code.

When you want to use dynamic import you use the import keyword. However, this time you call it as a function, and pass in path to the module as an argument. This function will return a promise. You can then consume that promise with the then handler. The loaded module is passed to then handler through parameter.

As an alternative to the then() handler, you can also use await keyword, and assign the module to a variable. Then, you can do whatever you want with that module.

// Example of dynamic import
import('./my-module.js')
  // Use then() handler to consume returned promise
  .then((module) => {
    // Do something with the module
    // returned by the promise
    // and passed through "module" parameter
  })

// Alternative with await
(async function() {
  // Assign the module to a variable
  const myModule = await import('./my-module.js')
  // Do something with that module
}())
Enter fullscreen mode Exit fullscreen mode

If you want to use await remember that you have to use async function. Well, unless you use top-level await which is another option. In that case, no need to use async function.

// Using top-level await
// Assign the module to a variable
const myModule = await import('./my-module.js')
// Do something with that module
Enter fullscreen mode Exit fullscreen mode

Conclusion: Import and export statements in JavaScript and how to use them

Import and export statements are two features that can be very handy. They can help you make your code clearer and easier to manage and maintain. What's more, they are both also very easy to learn and use. I hope that this tutorial helped you learn about what import and export statements are, how they work and how to use them.

文章来源:https://dev.to/alexdevero/import-and-export-statements-in-javascript-and-how-to-use-them-1cnm