AMD (异步模块定义)-浏览器
基本上,使用模块的方式很简单,import用于从另一个文件中获取功能或几个功能或值,同 时export用于从文件中公开功能或几个功能或值。
导出
使用 ES5 (CommonJS)
// 使用 ES5 CommonJS – helpers, js
exports. isNull = function (val) {
return val == null;
}
exports. isUndefined = function (val) {
return val = undefined;
}
exports. isNullOrUndefined = function (val) {
return exports. isNull(val) || exports.isUndefined(val); }
使用ES6模块 使用
ES6 Modules – helpers. js
export function isNull(val){
return val = null;
}
export function isUndefined(val) {
return val = undefined;
}
export function isNullOrUndefined(val) {
return isNull(val) || isUndefined(val);
}

在另一个文件中导入函数
// 使用 ES5 (CommonJS) – index. js
const helpers = require(‘. /helpers.js’); // helpers is an object
const isNull = helpers. isNull;
const isUndefined = helpers. isUndefined;
const isNullOrUndef ined = helpers. isNullOrUndefined;
// or if your environment supports Destructuring
const { isNull, isUndefined, isNullOrUndefined } = require(‘./helpers, js’);
// ES6 Modules – index, js
import * as helpers from ‘. /helpers.js’; // helpers is an object
// or
import { isNull, isUndefined, isNullOrUndefined as isValid } from ‘. /helpers.js’;
// using "as" for renaming named exports
在文件中导出单个功能或默认导出
使用 ES5 (CommonJS)
// 使用 ES5 (CommonJS) – index. js
class Helpers {
static isNull(val) {
return val == null;
}
static isUndefined(val) {
return val == undefined;
}
static isNu1lOrUndefined(va1) {
return this. isNull(val) || this.isUndefined(val);
)
}
module. exports = Helpers;
使用 ES6 Modules
// 使用 ES6 Modules – helpers. js
class Helpers {
static isNull(val) {
return val == null;
}
static isUndefined(val) {
return val = undefined;
}
static isNullOrUndefined(val) {
return this. isNull(val) || this.isUndefined(val);
}
}
export default Helpers
从另一个文件导入单个功能
使用 ES5 (CommonJS)
// 使用 ES5 (CommonJS) – index. js const Helpers = require(‘. /helpers. js’);
console. log(Helpers. isNull(null));
使用 ES6 Modules
import Helpers from ‘.helpers.js’ console. log(Helpers. isNull(null));

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.