美文网首页
JS module 导入与导出(commonJS、ES6)

JS module 导入与导出(commonJS、ES6)

作者: 九三的故事 | 来源:发表于2019-06-28 21:57 被阅读0次

commonJS 规范导出、commonJS 规范导入

// 导出对象
module.exports  = {
    add: function() {}
}

// 导入
const api = require('api.js');

// 使用
api.add();


// 导出方法
module.exports = function() {}

// 导入
const add = require('add.js');

// 使用
add();

ES6导出、ES6导入

// 默认导出
export default function() {}

// 导入
import add from 'api.js';
import { default as add } from 'api.js'; // 或使用

// 使用
add();

// 对象导出
export const add = function() {}
export const del = function() {} 

// 对象导入
import { add, del } from 'api.js';

// 使用
add();

// 或者想导入所有
import * as api from 'api.js';

// 使用
api.add();

commonJS 规范导出,ES6 规范导入

// 导出
module.exports = {
    add: function() {}
}

// 导入
import api from 'api.js';

// 使用
api.add();

// 或者
import { add } from 'api.js';

// 使用
add();

ES6 规范导出、common.JS 导入

// 导出
export const add = function() {}

// 导入
const api = require('api.js');

// 使用
api.add();

// 默认导出
export default function() {}

// 导入
const add = require('api.js').default;

// 使用
add();

相关文章

网友评论

      本文标题:JS module 导入与导出(commonJS、ES6)

      本文链接:https://www.haomeiwen.com/subject/tsjycctx.html