以Java來說,比如要實現第三方存儲,我可能需要導入對應的庫,以maven為例,使用騰訊雲或者七牛雲、阿里雲,我需要導入對應的maven依賴。
再比如,有些時候我們封裝某個類,而那個類不在該包下,我們需要導包(就是指定那個類的路徑,如果路徑不對,則可能出現找不到這個類之類的錯誤,通常對應的IDE會提示錯誤)。
其實,node.js也是這樣的。最近在開發node.js的時候,難免也會遇到需要引入其它js文件。今天我以一個簡單示例來說一說node.js如何引用其它js文件。
test01.js
function hello(){ console.log("hello"); } function hello2(){ console.log("hello2"); } module.exports = {hello,hello2}
test02.js
var test01 = require( "./test01" ); test01.hello(); test01.hello2();
通過命令行運行node test02.js 正常會分別輸出hello、hello2。
require是什么意思呢?
其實就跟我們Java開發導包一樣的意思,在Java中是import,其實node.js也可以import式導包。
那么node.js中的require和import導包有什么區別呢?
(1)require導包位置任意,而import導包必須在文件的最開始;
(2)遵循的規范不同,require/exports是CommonJS的一部分,而import/export是ES6的規范;
(3)出現時間不同,CommonJS作為node.js的規范,一直沿用至今,主要是因為npm善CommonJS的類庫眾多,以及CommonJS和ES6之間的差異,Node.js無法直接兼容ES6。所以現階段require/exports仍然是必要且必須的;
(4)形式不同,require/exports的用法只有以下三種簡單寫法:
const fs = require('fs'); — — — — — — — — — — — — — — exports.fs = fs; module.exports = fs;
而import/exports的寫法就多種多樣
import fs from 'fs'; import {default as fs} from 'fs'; import * as fs from 'fs'; import {readFile} from 'fs'; import {readFile as read} from 'fs'; import fs, {readFile} from 'fs'; — — — — — — — — — — — — — — — — — — — — export default fs; export const fs; export function readFile; export {readFile, read}; export * from 'fs';
(5)本質上不同,主要體現:
a.CommonJS還是ES6 Module 輸出都可以看成是一個具備多個屬性或者方法的對象;
b.default是ES6 Module所獨有的關鍵字,export default fs 輸出默認的接口對象,import fs from ‘fs’可直接導入這個對象;
c.ES6 Module 中導入模塊的屬性或者方法是強綁定的,包括基礎類型,而CommonJS則普通的值傳遞或者引用傳遞;
本文參考鏈接如下所示:
node.js如何引用其它js文件:https://www.cnblogs.com/wuotto/p/9640312.html
關於require/import的區別:https://www.jianshu.com/p/fd39e16feb60