# ES6 Modules and CommonJS (Oke) Một ví dụ quý hơn vàng :(((

Sử dụng từ khóa import && export trong javascript :(((

index.html

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
    <script type="module">
	    import {addTextToBody, Human} from './custom.js';
	    addTextToBody("Hello World");
	    const human = new Human;
	    human.show();
	  </script>
</body>
</html>
```

custom.js

```
// custom.js
export const addTextToBody = text => {
  const div = document.createElement('div')
  div.textContent = text
  document.body.appendChild(div)
}
export class Human {
  show() {
    console.log("Human: Hello world!")    
  }  
}
```

## Ở đây tôi có sử dụng hai từ khóa mà trước đó tôi tìm mãi không được :))

```
export, import :)
```

Hoặc ví dụ tiếp theo

{% embed url="<https://o7planning.org/vi/12181/huong-dan-ecmascript-module>" %}

{% file src="<https://2726517656-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M1E4Gk2ppVKb4olmnun%2F-M30W1IDRIsXK0Uj0VLq%2F-M30fOUn-iPj5nBfakEt%2Ftyscripte.rar?alt=media&token=6b00ca75-38a1-425d-8f5c-1725506e3072>" %}

## Hướng dẫn sử dụng ECMAScript Module

**Xem thêm các chuyên mục:**

* [Các hướng dẫn ECMAScript, Javascript](https://o7planning.org/vi/12171/ecmascript-javascript)

Nhóm thành viên của o7planning đã xây dựng một website tuyệt vời và miễn phí giúp mọi người học tiếng Anh, học từ vựng dễ dàng hơn. Hãy truy cập để học tiếng Anh ngay bây giờ:

* [langlearning.net](http://langlearning.net/)

1- ES Module2- Các cú pháp ES Import3- NodeJS - CommonJS Module4- ES6 Module trong NodeJS4Shares![facebook sharing button](https://platform-cdn.sharethis.com/img/facebook.svg)![twitter sharing button](https://platform-cdn.sharethis.com/img/twitter.svg)![pinterest sharing button](https://platform-cdn.sharethis.com/img/pinterest.svg)![linkedin sharing button](https://platform-cdn.sharethis.com/img/linkedin.svg)![reddit sharing button](https://platform-cdn.sharethis.com/img/reddit.svg)![odnoklassniki sharing button](https://platform-cdn.sharethis.com/img/odnoklassniki.svg)![vk sharing button](https://platform-cdn.sharethis.com/img/vk.svg)![tumblr sharing button](https://platform-cdn.sharethis.com/img/tumblr.svg)![blogger sharing button](https://platform-cdn.sharethis.com/img/blogger.svg)![wechat sharing button](https://platform-cdn.sharethis.com/img/wechat.svg)![email sharing button](https://platform-cdn.sharethis.com/img/email.svg)

### 1- ES Module

**ECMAScript 6** giới thiệu **ES6 Module Syntax** giúp các lập trình viên module hóa (modularize) code của họ. Nói một cách đơn giản bạn có thể viết code của bạn trên các tập tin riêng rẽ. Trên tập tin này bạn có thể xuất khẩu ( **export**) những thứ cần thiết dưới dạng các **module**, các tập tin khác có thể nhập khẩu ( **import**) các **module** của tập tin đó để sử dụng.![](https://o7planning.org/vi/12181/cache/images/i/29449072.png)**Module** và **import/export** là ý tưởng tuyệt vời giúp bạn dễ dàng quản lý và bảo trì code trong các ứng dụng lớn. Code mà bạn viết trong một tập tin được bảo hộ chỉ những gì bạn xuất khẩu dưới dạng một **module** mới có thể được truy cập từ một tập tin khác.Để đơn giản, ở đây tôi tạo ra 2 tập tin **es6-module-file.js & es6-file1.js**.

* **es6-module-file.js**: Tập tin này định nghĩa ra các hằng số, hàm, các lớp,... Một vài thứ trong chúng được đóng gói trong cùng một **module** và xuất khẩu **module** này ra bên ngoài.
* **es6-file1.js**: Là một tập tin nhập khẩu một vài **module** của tập tin **es6-module-file.js** để sử dụng.

![](https://o7planning.org/vi/12181/cache/images/i/29449409.png)se6-module-file.js?

| 12345678910111213141516171819202122232425262728293031323334 | `// Constantsconst` `HELLO =` `"Hello Everybody";const` `BYE =` `"Goodbye!";` `// Private function (Do not export this function)function` `doSomething()  {   console.log("Do Something");}` `// A Functionlet` `sayHello =` `function(name)  {  if(name)  {    console.log("Hello "` `+ name);  }` `else` `{    console.log(HELLO);  }}` `// A Functionlet` `sayGoodbye =` `function(name)  {  if(name)  {    console.log("Goodbye "` `+ name);  }` `else` `{    console.log(BYE);  }}` `// Export a Moduleexport` `{HELLO, BYE, sayHello, sayGoodbye};` `// Export as default Module.// IMPORTANT!!: Allow at most one 'default'export` `default` `{sayHello, sayGoodbye};` |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Tập tin **es6-file1.js** nhập khẩu một vài **module** của tập tin **es6-module-file.js**:es6-file1.js?

| 12345678910 | `// Import *import` `* as myModule from` `'./es6-module-file.js';` `console.log( myModule.HELLO );` `// Hello Everybodyconsole.log( myModule.BYE );` `// Goodbye!` `myModule.sayHello("Tom")  ;` `// Hello Tom` `myModule.sayGoodbye("Tom")  ;// Goodbye Tom` |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Để thử nghiệm ví dụ, cách đơn giản nhất là tạo một tập tin **HTML**, chẳng hạn **test1.html**:

> Chú ý: Bạn phải sử dụng **\<script type="module">** thay vì **\<script type="text/javascript">**.

es6-test1.html?

| 12345678910111213141516 | `<!DOCTYPE html><html><head><meta` `charset="UTF-8"><title>Import/Export</title>` `<!-- IMPORTANT!! type = "module" -->   <script` `type="module"` `src="es6-file1.js"></script>` `</head>` `<body>  Show informations in the Console.</body>` `</html>` |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Bạn cần chạy tập tin **es6-test1.html** trên một **HTTP Server**, và bạn có thể nhìn thấy kết quả trên cửa sổ **Console** của trình duyệt. Chú ý: **ES6 Module** sẽ không hoạt động nếu bạn chạy trực tiếp tập tin **HTML** trên trình duyệt với **schema file:///**.![](https://o7planning.org/vi/12181/cache/images/i/29766154.png)

#### NodeJS!

> Nếu bạn nhận được lỗi dưới đây trong khi chạy tập tin **es6-file1.js** trên **NodeJS**. Bạn có thể xem giải thích ở phía cuối của bài viết này.?

| 123456789101112131415 | `C:\webexamples\node-ecmascript\module\es6-file1.js:2import * as myModule from './es6-module-file.js';^^^^^^` `SyntaxError: Unexpected token import    at createScript (vm.js:80:10)    at Object.runInThisContext (vm.js:139:10)    at Module._compile (module.js:617:28)    at Object.Module._extensions..js (module.js:664:10)    at Module.load (module.js:566:32)    at tryModuleLoad (module.js:506:12)    at Function.Module._load (module.js:498:3)    at Function.Module.runMain (module.js:694:10)    at startup (bootstrap_node.js:204:16)    at bootstrap_node.js:625:3` |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

### 2- Các cú pháp ES Import

Import Syntaxes?

| 1234567891011 | `import` `defaultExport from` `"module-name";import` `* as name from` `"module-name";import` `{` `export` `} from` `"module-name";import` `{` `export` `as alias } from` `"module-name";import` `{ export1 , export2 } from` `"module-name";import` `{ foo , bar } from` `"module-name/path/to/specific/un-exported/file";import` `{ export1 , export2 as alias2 , [...] } from` `"module-name";import` `defaultExport, {` `export` `[ , [...] ] } from` `"module-name";import` `defaultExport, * as name from` `"module-name";import` `"module-name";var` `promise =` `import("module-name");` |
| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Ví dụ:es6-file1.js?

| 123456789 | `// Syntax: import * as name from "Module-name or File-path";import` `* as myModule from` `'./es6-module-file.js';` `console.log( myModule.HELLO );` `// Hello Everybodyconsole.log( myModule.BYE );` `// Goodbye!` `myModule.sayHello("Tom")  ;` `// Hello Tom` `myModule.sayGoodbye("Tom")  ;// Goodbye Tom` |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Ví dụ:es6-file2.js?

| 123456 | `// Syntax: import { export1 , export2 } from "Module-name or File-path";import` `{sayHello, HELLO} from` `'./es6-module-file.js';` `console.log(  HELLO );` `// Hello Everybody` `sayHello("Tom")  ;` `// Hello Tom` |
| ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Ví dụ:es6-file3.js?

| 123456 | `// Syntax: import { export as alias } from "Module-name or File-path";import` `{sayHello as mySayHello, HELLO} from` `'./es6-module-file.js';` `console.log(  HELLO );` `// Hello Everybody` `mySayHello("Tom")  ;` `// Hello Tom` |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Ví dụ:es6-file4.js?

| 1234567 | `// Syntax: import { export as alias } from "Module-name or File-path";import` `{sayHello as mySayHello, HELLO} from` `'./es6-module-file.js';` `console.log(  HELLO );` `// Hello Everybody` `mySayHello("Tom")  ;` `// Hello Tom` |
| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Ví dụ:es6-file5.js?

| 1234567 | `// Syntax: import defaultExport, * as name from "Module-name or File-path";import` `myModule, {sayHello, HELLO} from` `'./es6-module-file.js';` `console.log(  HELLO );` `// Hello Everybody` `myModule.sayHello("Tom")  ;` `// Hello Tom` |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

### 3- NodeJS - CommonJS Module

> * [Hướng dẫn sử dụng NodeJS Module](https://o7planning.org/vi/11937/huong-dan-nodejs-module)

**NodeJS** sử dụng một cú pháp của riêng nó để xuất khẩu và nhập khẩu một **Module**, cú pháp này thường được biết đến với tên gọi **"CommonJS Module Syntax"**. Chúng ta hãy xem một ví dụ với cú pháp này:![](https://o7planning.org/vi/12181/cache/images/i/29842947.png)nodejs-module-file.js?

| 1234567891011121314151617181920212223242526272829 | `// Constantsconst` `HELLO =` `"Hello Everybody";const` `BYE =` `"Goodbye!";` `// Private function (Do not export this function)function` `doSomething()  {   console.log("Do Something");}` `// A Functionlet` `sayHello =` `function(name)  {  if(name)  {    console.log("Hello "` `+ name);  }` `else` `{    console.log(HELLO);  }}` `// A Functionlet` `sayGoodbye =` `function(name)  {  if(name)  {    console.log("Goodbye "` `+ name);  }` `else` `{    console.log(BYE);  }}` `// Export a Module (CommonJS Module Syntax)module.exports = {HELLO, BYE, sayHello, sayGoodbye};` |
| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

Tập tin **nodejs-file1.js** nhập khẩu một vài **module** của tập tin **nodejs-module-file.js**:nodejs-file1.js?

| 123456789 | `// Importvar` `myModule = require("./nodejs-module-file.js");` `console.log( myModule.HELLO );` `// Hello Everybodyconsole.log( myModule.BYE );` `// Goodbye!` `myModule.sayHello("Tom")  ;` `// Hello Tom` `myModule.sayGoodbye("Tom")  ;// Goodbye Tom` |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Chạy trực tiếp tập tin **nodejs-file1.js** trên môi trường **NodeJS**:![](https://o7planning.org/vi/12181/cache/images/i/29842990.png)

### 4- ES6 Module trong NodeJS

Có nhiều cú pháp **Module** đang được sử dụng đồng thời trong **Javascript**, chẳng hạn **CommonJS Module Syntax**, **ES6 Module Syntax**,..

* **NodeJS** sử dụng **CommonJS Module Syntax** để xuất khẩu và nhập khẩu một **module**. Cụ thể nó sử dụng từ khóa **module.exports/required()** thay vì **export/import**.
* **ES6 Module Syntax** sử dụng từ khóa **export/import** để xuất khẩu và nhập khẩu một **module**.

Mặc dù **ES6 Module Syntax** được giới thiệu trong phiên bản **ECMAScript6** (Phát hành năm 2015), nhưng **NodeJS** phiên bản 11 (Phát hành tháng 10 năm 2018) vẫn không hỗ trợ cú pháp này theo mặc định, vì vậy khi thực thi tập tin **Javascript** có sử dụng **ES Module Syntax** trên **NodeJS** bạn có thể gặp một lỗi tương tự dưới đây:?

| 12345 | `C:\webexamples\node-ecmascript\module\es6-file1.js:1(function (exports, require, module, __filename, __dirname) { import { sayHello } from './es6-file1.js';                                                              ^^^^^^` `SyntaxError: Unexpected token import` |
| ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Giải pháp ở đây là bạn cần đổi tên các tập tin **\*.js** thành **\*.mjs (Module JS)**. Ví dụ ở đây tôi tạo 2 tập tin **mjs**:![](https://o7planning.org/vi/12181/cache/images/i/29847725.png)es6node-module-file.mjs?

| 1234567891011121314151617181920212223242526272829 | `// Constantsconst` `HELLO =` `"Hello Everybody";const` `BYE =` `"Goodbye!";` `// Private function (Do not export this function)function` `doSomething()  {   console.log("Do Something");}` `// A Functionlet` `sayHello =` `function(name)  {  if(name)  {    console.log("Hello "` `+ name);  }` `else` `{    console.log(HELLO);  }}` `// A Functionlet` `sayGoodbye =` `function(name)  {  if(name)  {    console.log("Goodbye "` `+ name);  }` `else` `{    console.log(BYE);  }}` `// Export a Moduleexport` `{HELLO, BYE, sayHello, sayGoodbye};` |
| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

es6node-file1.mjs?

| 12345678910 | `// Import *import` `* as myModule from` `'./es6node-module-file.mjs';` `console.log( myModule.HELLO );` `// Hello Everybodyconsole.log( myModule.BYE );` `// Goodbye!` `myModule.sayHello("Tom")  ;` `// Hello Tom` `myModule.sayGoodbye("Tom")  ;// Goodbye Tom` |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |

Mở cửa sổ **CMD** và **CD** vào thư mục chứa 2 tập tin trên và thực thi lệnh sau:?

| 1 | `node --experimental-modules es6node-file1.mjs` |
| - | ----------------------------------------------- |

![](https://o7planning.org/vi/12181/cache/images/i/29453022.png)

**Xem thêm các chuyên mục:**

* [Các hướng dẫn ECMAScript, Javascript](https://o7planning.org/vi/12171/ecmascript-javascript)
