require和import的区别和使用

最近在学习node,刚开始不明白为什么写node的时候,不能用import而只能用require,Node对CommonJS模块规范的实现, CommonJS模块基本上包括两个基础的部分:一个取名为exports的自由变量,它包含模块希望提供给其他模块的对象,以及模块所需要的可以用来引入和导出其它模块的函数, 所以node.js里面导出使用module.exports = 模块名,引入的时候使用require

相关资料:
官方地址: http://nodejs.cn/api/modules.html
commonJs的知识链接: https://www.w3cschool.cn/zobyhd/1ldb4ozt.html
es6: https://es6.ruanyifeng.com/#docs/module

下面是node中使用的CommonJS的部分说明The module.syncBuiltinESMExports() method updates all the live bindings for builtin ES Modules to match the properties of the CommonJS exports

require和import的区别:
CommonJS 模块就是对象,输入时必须查找对象属性

// CommonJS模块
let { stat, exists, readfile } = require('fs');

// 等同于
let _fs = require('fs');
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;

整体加载fs模块(即加载fs的所有方法),生成一个对象(_fs),然后再从这个对象上面读取 3 个方法。这种加载称为“运行时加载”,因为只有运行时才能得到这个对象,导致完全没办法在编译时做“静态优化”

ES6 模块不是对象,而是通过export命令显式指定输出的代码,再通过import命令输入

// 输出
export const test = '11111'
export const exists= '11111'
export const readFile = '11111'
// ES6模块
import { test , exists, readFile } from 'fs';

上面的代码也可以写成:

// 输出
 const test = '11111'
 const exists= '11111'
 const readFile = '11111'
 export { test, exists, readFile }

上面代码的实质是从fs模块加载 3 个方法,其他方法不加载。这种加载称为“编译时加载”或者静态加载,即 ES6 可以在编译时就完成模块加载,效率要比 CommonJS 模块的加载方式高。当然,这也导致了没法引用 ES6 模块本身,因为它不是对象。

export 和export default 区别:
export输出的时候 import必须要知道函数名,所以如果使用者不想去查函数命是什么,可以使用export default输出一个模块,然后import直接用,不用去查函数名是什么

// export-default.js
export default function () {
  console.log('foo');
}

使用:

// import-default.js
import customName from './export-default';
customName(); // 'foo'
原文地址:https://www.cnblogs.com/antyhouse/p/13278833.html