import路径
import {test} from \'./test\';
花括号
import {test} from \'./test\';
import test from \'./test\';
如果有默认导出export default则可以省略花括号,且import的模块名是随意的,如:
// a.js
export default \'test\';
// b.js
import a from \'./a\';
import A from \'./a\';
import myA from \'./a\';
非export default导出的模板名,在引用时须加花括号,且引用模块名与导出时的命名必须相同,如:
// a.js
export const a = \'test\';
// b.js
import {a} from \'./a\';
import {A} from \'./a\'; // error
import {myA} from \'./a\'; // error
一个模块中只允许一个默认导出export default,但允许多个命名导出export;
路径
import test from \'test\';
import test from \'./test\';
babel默认会把ES6的模块转化为commonjs规范。
import test from \'X\';
// 等价于
var test = require(\'X\');
查找规则:
-
如果
X是内置模块,则直接返回该模块。如require(\'http\')。 -
如果
X以./、/、../开头:- 根据
X所在的父模块,确定X的绝对路径。 - 将
X当做文件,依次查找下面的文件,如果找到,则直接返回。XX.jsX.jsonX.node
- 将
X当做目录,依次查找下面的文件,如果找到,则直接返回。X/package.json(查找main字段中的文件,规则同上)X/index.jsX/index.jsonX/index.node
- 根据
-
如果
X不带路径:- 根据
X所在的父模块,确定X可能的安装目录。 - 依次在每个目录中,将
X当成文件名或目录名加载。
- 根据
-
\"not found\"
模块格式
CommonJS
同步加载模块,主要用于服务端(node)。
// math.js
exports.add = function(a, b) {
return a + b;
}
// main.js
var math = require(\'./math\');
math.add(2, 3); // 5
AMD
异步模块定义,用于像RequireJS这样的模块加载器,主要用于浏览器。
// math.js
define(function() {
var add = function(x, y) {
return x + y;
}
return {
add: add
}
})
// main.js
require([\'math\'], function(math) {
alert(math.add(1, 1));
})
UMD
(function (root, factory) {
if (typeof define === \'function\' && define.amd) {
// AMD. Register as an anonymous module.
define([], factory);
} else if (typeof module === \' \' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(typeof self !== \'undefined\' ? self : this, function () {
// Just return a value to define the module export.
// This example returns an , but the module
// can return a function as the exported value.
return {};
}));
ES6
es6通过import、export实现模块的输入输出
参考资料
继续阅读与本文标签相同的文章
上一篇 :
python简单实现图片转字符
下一篇 :
立体库入库如何防止货位超重?
-
选择按钮搭配VBA实现数据小型自动化
2026-05-18栏目: 教程
-
Python高级进阶#011 pyqt5按钮QPushButton应用
2026-05-18栏目: 教程
-
Apache Solr Velocity模版注入远程命令执行漏洞复线
2026-05-18栏目: 教程
-
从订货会的功能变迁看出版业的沧海桑田
2026-05-18栏目: 教程
-
ASP.NET Core on K8S深入学习(9)Secret & Configmap
2026-05-18栏目: 教程
