---
# System prepended metadata

title: ES6 Module 匯出 與 加載
tags: [Export, ES6, Import, JavaScript]

---

# ES6 Module 匯出 與 加載

###### tags: `ES6` `JavaScript` `Export` `Import`

## export default 語法糖

舉例： parseQueryString.js
```
import decodeUriComponent from "decode-uri-component";

function parseQueryString(url) {
  var obj = {};
  var keyvalue = [];
  var key = "",
    value = "";
  var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
  for (var i in paraString) {
    keyvalue = paraString[i].split("=");
    key = keyvalue[0];
    value = decodeUriComponent(keyvalue[1]);
    obj[key] = value;
  }
  return obj;
}

export default parseQueryString;

```

使用： 直接匯入便可以直接當作function使用
```
import parseQueryString from "[paht]/parseQueryString.js";

let query_obj = parseQueryString(location.href);
```

## 多個使用一次匯出

舉例： parseQueryString.js
```
function function1() {
  ...
}
function function2() {
  ...
}

export {function1, function2};
```


```
import * as myFunction from './cow.js'

myFunction.function1();
myFunction.function2();
```

## vue動態加載module的方式

import是靜態加載，在編譯前就會解析，因此沒辦法做if那些執行時的判斷語句，所以要用required動態加載的方式

範例：
```
var MyHeader;
var MyFooter;
if (window.location.pathname.slice(1) == "notice.html") {
  MyHeader = require("../components/index_header.vue").default;
  MyFooter = require("../components/index_footer.vue").default;
} else if (window.location.pathname.slice(1) == "group_notice.html") {
  MyHeader = require("../components/index_group_header.vue").default;
  MyFooter = require("../components/index_group_footer.vue").default;
} else if (window.location.pathname.slice(1) == "subsidiary_notice.html") {
  MyHeader = require("../components/index_subsidiary_header.vue").default;
  MyFooter = require("../components/index_footer.vue").default;
} else if (window.location.pathname.slice(1) == "parent_notice.html") {
  MyHeader = require("../components/index_parent_header.vue").default;
  MyFooter = require("../components/index_footer.vue").default;
}
```
