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

https://viblo.asia/p/javascript-promises-classes-es6-modules-and-commonjs-07LKX48DKV4

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

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

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

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ờ:

1- ES Module2- Các cú pháp ES Import3- NodeJS - CommonJS Module4- ES6 Module trong NodeJS4Sharesfacebook sharing buttontwitter sharing buttonpinterest sharing buttonlinkedin sharing buttonreddit sharing buttonodnoklassniki sharing buttonvk sharing buttontumblr sharing buttonblogger sharing buttonwechat sharing buttonemail sharing button

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.Moduleimport/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.

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:///.

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

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

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

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ổ CMDCD 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

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

Last updated

Navigation

Lionel

@Copyright 2023