Advertisement
duongntb94

[Feature] [JS] CJS, AMD, UMD, and ESM

Oct 21st, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // 1. CJS là commonJS. Chạy synchronous và sử dụng cho backend, hay sử dụng cho NodeJS
  2. //importing
  3. const doSomething = require('./doSomething.js');
  4.  
  5. //exporting
  6. module.exports = function doSomething(n) {
  7.   // do something
  8. }
  9.  
  10. // 2. AMD stands for Asynchronous Module Definition. Chạy asynchronous và sử dụng cho front end.
  11. define(['dep1', 'dep2'], function (dep1, dep2) {
  12.     //Define the module value by returning a value.
  13.     return function () {};
  14. });
  15.  
  16. // 3. UMD stands for Universal Module Definition. Sử dụng được cho front end và backend, và thường được gọi fallback cho ESM nếu ko run được ESM
  17. (function (root, factory) {
  18.     if (typeof define === "function" && define.amd) {
  19.         define(["jquery", "underscore"], factory);
  20.     } else if (typeof exports === "object") {
  21.         module.exports = factory(require("jquery"), require("underscore"));
  22.     } else {
  23.         root.Requester = factory(root.$, root._);
  24.     }
  25. }(this, function ($, _) {
  26.     // this is where I defined my module implementation
  27.  
  28.     var Requester = { // ... };
  29.  
  30.     return Requester;
  31. }));
  32.  
  33. // 4. ESM stands for ES Modules. Chạy front end và backend. Có thể import vào trình duyệt
  34. import {foo, bar} from './myLib';
  35.  
  36. ...
  37.  
  38. export default function() {
  39.   // your Function
  40. };
  41. export const function1() {...};
  42. export const function2() {...};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement