module.exports 、 exports 和 export 、 export default 、 import

流火行者發表於2017-08-09
 1 1:commonjs規範
 2 module.exports={a:10,b:20}
 3 var test=require('lib/test')
 4 console.log(test.a);console.log(test.b);
 5 
 6 module.exports = function(name, age) { 
 7      this.name = name; 
 8      this.age = age; 
 9      this.about = function() { 
10           console.log(this.name +' is '+ this.age +' years old'); 
11      }; 
12 }; 
13 var Rocker = require('./rocker.js'); 
14 var r = new Rocker('Ozzy', 62); 
15 r.about(); 
16 
17 
18 module.exports.a=[1,2,3]
19 module.exports.b={a:10,b:20}
20 var test=require('lib/test')
21 console.log(test.a);console.log(test.b);
22 
23 exports.a={a:10,b:20}
24 注:module.exports優先有效,沒有則將exports取到賦給module.exports
25 
26 2:ES6規範
27 export var a=1
28 export function fun1(a,b){
29     return a+b
30 }
31 export const PI='3.1415925'
32 //export default每個檔案只能有一個
33 export default {
34     a:10,
35     b:20
36 }
37 import('lib/utils') 動態載入 類似於commonjs的require('lib/utils')
38 import {a,b} from 'utils'
39 import * as utils from 'utils'
View Code

 

http://javascript.ruanyifeng.com/nodejs/module.html

http://es6.ruanyifeng.com/#docs/module

補充:如果要import的檔案使用export default匯出,直接import utils from "@/lib/utils"即可

原文地址:http://www.cnblogs.com/JimmyBright/p/7326848.html

 

相關文章