search
HomeWeb Front-endFront-end Q&AWhat does export mean in javascript

In JavaScript, export means "export"; all declarations within a module in JavaScript are local. The module can be exported using the export keyword. This command can appear anywhere in the module to export the module. Then other JS files can load the module through the import command.

What does export mean in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

What does export mean in javascript

By default, all declarations in JavaScript modules are local and cannot be made externally access. If you need to expose some of the declared content in the module and let other modules use it, you need to export the function. The simplest way is to add the export keyword to export the module.

The content that can be exported includes classes, functions, and variables modified by var, let, and const. The export command can appear anywhere in the module, as long as it is at the top level of the module. If it is in block-level scope, an error will be reported, as will the import command.

After using the export command to define the external interface of the module, other JS files can load this module through the import command.

The import command has a lifting effect and will be promoted to the head of the entire module and executed first. Since import is executed statically, expressions and variables cannot be used. These are syntax structures whose results can only be obtained at runtime.

1. Default import and export default import/export

Each module has only one default export, and the export content can be a function, class, object, etc. Because this method is regarded as the main export content, the import method is the simplest.

// there is no semi-colon here
export default function() {} 
export default class {}
//示例
class A extends Component{
   ...
}
export default A;
//对应的import示例。
import A from './requireTest'
//default export, 输入 lodash 模块
import _ from 'lodash';
//一条import语句中,同时输入默认方法和其他变量
import _, { each } from 'lodash';
//上述代码对应的export语句
export default function (obj) {
  // ···
}
export function each(obj, iterator, context) {
  // ···
}
export { each as forEach };

Note: A module is only allowed to export one default object. What is actually exported is a variable named default for renaming. The equivalent statement is as follows. Therefore, any variable name can be used after import, and {} is not required.

import any from './requireTest'
import {default as any } from './requireTest'

2. Named import and export

It should be noted that the export command specifies the external interface and must establish a one-to-one correspondence with the variables inside the module. . In addition, the interface output by the export statement has a dynamic binding relationship with its corresponding value, that is, through this interface, the real-time value inside the module can be obtained.

The import command accepts a pair of curly brackets, which specifies the variable name to be imported from other modules. The variable name inside the curly brackets must be the same as the name of the external interface of the imported module (profile.js). If you want to rename the input variable, use the as keyword in the import command to rename the input variable.

The "from" after import specifies the location of the module file, which can be a relative path or an absolute path. The .js path can be omitted. If it is just the module name without a path, then there must be a configuration file to tell the JavaScript engine the location of the module.

// profile.js
//第一种export
export var firstName = 'Michael';
export function f() {};
//第二种export,优先使用这种写法
var firstName = 'Michael';
export {firstName};
function f() {}
export {f};
//main.js
import { firstName, f } from './profile';
import { firstName as surname } from './profile';

3. Rename import and export

export { myFunction }; // exports a function declared earlier
export const foo = Math.sqrt(2); // exports a constant

When importing the export content of different modules, the uniqueness of the naming must be maintained. This can be solved by renaming, including the following two categories.

//导出的时候重命名
function v1() { ... }
function v2() { ... }
export {
      v1 as streamV1,
      v2 as streamV2,
      v2 as streamLatestVersion  //可以用两个不同的名称导出相同的值
};
//导入的时候重命名
// 这两个模块都会导出以`flip`命名的东西。同时导入两者,需要将其中一个的名称改掉。
import {flip as flipOmelet} from "eggs.js";
import {flip as flipHouse} from "real-estate.js";

4. Compound writing method of export and import

If in a module, input first and then output the same module, the import statement can be written with the export statement. Together.

export { foo, bar } from 'my_module';
// 等同于
import { foo, bar } from 'my_module';
export { foo, bar };

【Related recommendations: javascript learning tutorial

The above is the detailed content of What does export mean in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor