Web Front-end
JS Tutorial
Introduction to JavaScript module export and import (detailed explanation)Introduction to JavaScript module export and import (detailed explanation)
This article brings you an introduction (detailed explanation) about JavaScript module export and import. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I recently looked at some programs written in the Vue framework and found that my front-end knowledge was still a few years ago. I found that there are various imports of modules in Javascript programs now. At first glance, the imports It is quite similar to the syntax of python, except that the two keywords from and import are used in the reverse order. If you look carefully, the import module is quite different from Python. The premise is that the module has exports, and it is also divided into default exports and named exports, which is a bit troublesome. So today’s article summarizes all export forms and corresponding import uses.
ES6 implements module functions at the level of language standards and becomes a universal module solution for browsers and servers. It can completely replace CommonJS and AMD specifications. The basic features are as follows:
Each module is only loaded once, and each JS is only executed once. If you load the same file in the same directory next time, it will be read directly from the memory;
Every The variables declared in a module are all local variables and will not pollute the global scope;
Variables or functions inside the module can be exported through export;
-
A module can import other modules
2. The module function mainly consists of two commands: export and import. The export command is used to specify the external interface of the module, and the import command is used to input the functions provided by other modules;
3. A module is an independent file, and all variables inside the file cannot be obtained externally. If you want the outside to be able to read a variable inside the module, you must use the export keyword to output the variable;
var year = '2018';
var month = 'Febuary';
export {year, month};
export export module
export syntax statement is used to export functions, objects, Specifies the original value of the file (or module). There are two module export methods: named export (name export) and default export (definition export) . Each module can have multiple named exports, while each default export Only one module.
Named export
The module can declare the export object through the export prefix keyword, and the export object can be multiple. These export objects are distinguished by names, which are called named exports
export { func }; // 导出一个已定义的函数func
export const foo = Math.sqrt(100); // 导出一个常量
We can use the * and from keywords to implement module inheritance:
export * from 'base_module';
When exporting a module, you can specify the module exported members. Exported members can be considered as public members in the class, while non-exported members can be considered as private members in the class:
var name = 'Kevin的居酒屋';
var domain = 'http://coffee.toast.com';
export {name, domain}; // 相当于导出{name:name,domain:domain}
When the module is exported, we can use the as keyword to rename the exported members, as shown above Export can be written like this:
export {name as siteName, domain}
Note the syntax errors:
export 1; var a = 100; export a;
When exporting the interface, it must have a one-to-one correspondence with the variables inside the module. Directly exporting 1 makes no sense, and it is impossible to have a variable corresponding to it when importing export aAlthough it seems to be true, the value of a is a number, and deconstruction cannot be completed at all, so it must be written as ## The form of #export {a}. Even if a is assigned to a function, it is not recommended to use the above form to export because most styles suggest that it is best to use an export at the end of the module to export all interfaces, just like the examples above.
export default function() {}; // 导出一个函数
export default class(){}; // 导出一个类Default export can be understood as another form of named export. Default export can be considered as a named export using the default name. The following two export methods are equivalent:
const D = 123;
export default D;
export { D as default };When exporting a module using a name:
// "my-module.js" 模块
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
export { cube, foo };In another module (js file), we can like Quote as follows:
import { cube, foo } from 'my-module';
console.log(cube(3));
console.log(foo);When using the default export of a module:
// "my-module.js"模块
export default function (x) {
return x * x * x;
}In another module, we can quote as follows, which is simpler to use than name export:
import cube from 'my-module'; console.log(cube(3)); // 27import import moduleThe import syntax statement is used to import functions, objects, and the original values of specified files (or modules) from exported modules and scripts. The import module import corresponds to the export module export function. There are also two module import methods: named import (name import) and default import (definition import).
Note: The import must be placed at the beginning of the file, and no other logical code is allowed in front. This is consistent with the import style of all other programming languages.
Named importWe can insert imported members into the current scope by specifying a name. You can import a single member or multiple members:Note that the variables in the curly braces correspond to the variables after export
import {myMember} from "my-module";
import {foo, bar} from "my-module";
通过*符号,我们可以导入模块中的全部属性和方法。当导入模块全部导出内容时,就是将导出模块(’my-module.js’)所有的导出绑定内容,插入到当前模块(’myModule’)的作用域中:
import * as myModule from "my-module";
默认导入
在模块导出时,可能会存在默认导出。同样的,在导入时可以使用import指令导入这些默认值。直接导入默认值:
import defaultName from "my-module";
import myDefault, {foo, bar} from "my-module"; // 指定成员导入和默认导入
default关键字
// my-module.js
export default function() {}
// 等效于:
function func() {};
export {func as default};
在import的时候,可以这样用:
import a from './my-module';
// 等效于,或者说就是下面这种写法的简写
import {default as a} from './my-module';
这个语法糖的好处就是import的时候,可以省去{}。
简单的说,如果import的时候,你发现某个变量没有花括号括起来(没有*号),那么你在脑海中应该把它还原成有花括号的{default as ...}语法,所以import $,{each,map} from 'jquery';import后面第一个$是{default as $}的替代写法。
The above is the detailed content of Introduction to JavaScript module export and import (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment

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.

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.






