--- tags: Javascript disqus: hackmd --- # [JS]import & export 彙整幾個較常看到的用法,建議先看export再回頭看import 目的:透過整理,對這個題目能夠更熟悉些 [完全解析 JavaScript import、export](https://wcc723.github.io/development/2020/03/25/import-export/) ## import [import](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/import) >基礎範例 ```javascript= //number.js var a = 123; export default a; //index.js import a from './number.js'; console.log(a); //123 ``` >改名 ```javascript= //number.js var a = 123; export default a; //index.js import k from './number.js'; console.log(k); //123 ``` >引入多個 ```javascript= //number.js var a = '我'; var b = '愛'; var c = '你'; export {a, b, c}; //index.js import {a, c} from './number.js'; console.log(a + c); //'我你' ``` >引入多個+改名 ```javascript= //number.js var a = '我'; var b = '愛'; var c = '你'; export {a, b, c}; //index.js import {a, b as love, c} from './number.js'; console.log(a + love + c); //'我愛你' ``` >引入整個模塊 ```javascript= //number.js const apple = 'apple'; const banana = 'banana'; const waterMelon = 'waterMelon'; export {apple, banana, waterMelon}; //index.js import * as fruits from './number.js'; console.log(fruits.apple + '-' + fruits.waterMelon); //apple-waterMelon ``` >引入default+named ```javascript= //number.js const apple = 'apple'; const banana = 'banana'; const waterMelon = 'waterMelon'; const lemon = 'lemon'; export default lemon; export {apple, banana, waterMelon}; //index.js import lemon, {apple, banana as peach} from './number.js'; console.log(lemon + ' + ' + apple + ' + ' + peach); //lemon + apple + banana import lemon, * as fruits from './number.js'; console.log(lemon + ' + ' + fruits.apple + ' + ' + fruits.peach); //lemon + apple + banana ``` ## export [export](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Statements/export)可以指派函式、物件或變數 export有兩種輸出方法`default`與`named` * default 一個文件只能有一個 >基礎範例 ```javascript= //number.js var a = 123; export default a; //index.js import a from './number.js'; console.log(a); //123 ``` * named >基礎範例 ```javascript= //number.js var a = 123; export default {a}; //index.js import {a} from './number.js'; console.log(a); //123 ``` >傳多個 ```javascript= //number.js var a = '我'; var b = '愛'; var c = '你'; export {a, b, c}; //index.js import {a, b, c} from './number.js'; console.log(a + b + c); //'我愛你' ``` >改名 ```javascript= //number.js var a = 123; var b = 999; export {a as oneTwoThree, b}; //index.js import {oneTwoThree, b} from './number.js'; console.log(oneTwoThree + b); //1122 ``` ## 匯入 Side Effect 模組 >僅作為副作用(side effect)引入整個模塊,而不直接引入任何東西。這樣會在不引入實際數值的情況下,執行整個模塊的程式。 ```javascript= //sideEffect.js console.log('我直接執行整隻js-1'); (function() { console.log('我直接執行整隻js-2'); })(); //index.js import './sideEffect.js'; //我直接執行整隻js-1 //我直接執行整隻js-2 ``` ## node 最後:Node.js的`引入(require)` `輸出(module.exports)`方法不同,是因為它不支援的關係。 (不過現在node 13.2版本有支援了) ![import&export瀏覽器相容性](https://i.imgur.com/zdFO7eO.png)