原文連接:https://blog.csdn.net/liya_nan/article/details/81141244node
require 和 import,都是爲了JS模塊化使用。最近項目中,由於多人協同開發,出現了一個項目中同時使用了require 和 import 引入依賴的狀況。正常狀況下,一個項目中最好是對引入方式作一個規範。下面咱們就來看一下require 和 import的區別:es6
一.require
require是Commonjs的規範,node應用是由模塊組成的,聽從commonjs的規範。用法:模塊化
//a.js function test (args) { // body... console.log(args); } module.exports = { test }; //b.js let { test } = require('./a.js'); test('this is a test.');
require的核心概念:在導出的文件中定義module.exports,導出的對象類型不予限定(可爲任意類型)。在導入的文件中使用require()引入便可使用。本質上,是將要導出的對象,賦值給module這個對象的exports屬性,在其餘文件中經過require這個方法來訪問exports這個屬性。上面b.js中,require(./a.js) = exports 這個對象,而後使用es6取值方式從exports對象中取出test的值。ui
二.import
import是es6爲js模塊化提出的新的語法,import (導入)要與export(導出)結合使用。用法:this
//a.js: export function test (args) { // body... console.log(args); } // 默認導出模塊,一個文件中只能定義一個 export default function() {...}; export const name = "lyn"; //b.js: // _表明引入的export default的內容 import _, { test, name } from './a.js'; test(`my name is ${name}`);
3、commonjs模塊與ES6模塊的區別
1.commonjs輸出的,是一個值的拷貝,而es6輸出的是值的引用;spa
2.commonjs是運行時加載,es6是編譯時輸出接口;
---------------------
做者:liya_nan
來源:CSDN
原文:https://blog.csdn.net/liya_nan/article/details/81141244
版權聲明:本文爲博主原創文章,轉載請附上博文連接!.net