Các loại module của javascript:
- IIFE: Immediately Invoked Function Expression
- ESM Browser - Ecmascript Module
- ESM Server - Ecmascript Module
- CJS - CommonJS
- AMD (cách cũ) - Asynchronous Module Definition
- UMD - Universal Module Definition: dân chơi dùng được cả trên server lẫn trình duyệt
2. ESM Browser - Ecmascript Module
- Sử dụng trên trình duyệt:
- Bắt buộc khai báo phải có: type="module"
- Import thư viện khác: phải có địa chỉ cụ thể
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<blockquote> <!DOCTYPE html> <html lang="en"> <body> <h1>Javascript Modules</h1> <script type="importmap"> { "imports": { "vue": "https://cdnjs.cloudflare.com/ajax/libs/vue/3.0.0-beta.14/vue.esm-browser.js", "main": "./main.js" } } </script> <script type="module"> import * as Vue from 'vue' import * as Main from 'main' import * as Vuex from 'https://cdnjs.cloudflare.com/ajax/libs/vuex/4.0.0-beta.2/vuex.esm-browser.js' import * as Compo from './Compo.js' </script> </body> </html> </blockquote> - Nếu import thư viện không có đường dẫn chính xác sẽ có lỗi <blockquote> import React fromt 'react' Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../". </blockquote> - Nếu import nhầm sang thư viện của ESM server <blockquote> --> Uncaught ReferenceError: process is not defined </blockquote> |
3. ESM Server
- Trong module này thường có thêm các biến của server: process.env, ... ==> nên mới không dùng được cho browser
- Import thư viện khi không có đường dẫn cụ thể
import React fromt 'react'
--> tự động tìm trong folder node_modules
4. CJS
- Thằng này cài trên server
- Cú pháp khác lắm nhé
1 2 3 4 5 6 |
const jsonServer = require('json-server') const fakeData = require('./fake-data') module.exports = { data: '123456' } |
- Run nó bằng: "node ./main.js"
5. UMD
- UMD được sử dụng cả trên server lẫn client, nên cú pháp phải đáp ứng được cả 2
- Thứ nhất: phải là cú pháp dạng IIFE
1 2 3 4 5 6 7 8 9 10 11 12 13 |
(function (global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory() } else if (typeof define === 'function' && define.amd) { define(factory) } else { (global = global || self, global["module-name"] = factory()); } }(this, function () { 'use strict'; })); |
- Thứ 2: ... chưa viết đc tiếp 😀