require/exports 和 import/export 区别

时间:2021-05-21 23:18:46

零、区别

1、require/exports 是 CommonJS 的标准,适用范围如 Node.js

2、import/export 是 ES6 的标准,适用范围如 React

一、间接获取对象

(1)require/exports

module.js

exports.name = "colin";
exports.sayHello = function() {
    console.log("hello");
};

getModule.js

var myModule = require('./module');
console.log(myModule.name);
myModule.sayHello();

(2)import/export

module.js

export const name = 'colin';
export function sayHello(){
    console.log("hello");
}

getModule.js

import { name, sayHello } from './module'  
console.log(name);
sayHello();

二、直接获取对象

(1)require/exports

module.js

var name = "colin";
module.exports = name;

getModule.js

var name = require('./module');
console.log(name);

(2)import/export

module.js

export default name = 'colin';

getModule.js

import name from './module' 
console.log(name);