关于'es' | 'cjs' | 'umd' | 'iife' 相关介绍

2年前 (2022) 程序员胖胖胖虎阿
210 0 0

目前在用vite构建项目工具库发现一些知识盲区

ES

ECMAScript Module,现在使用的模块方案,使用 import export 来管理依赖
浏览器直接通过 <script type="module"> 即可使用该写法。NodeJS 可以通过使用 mjs 后缀或者在 package.json 添加 "type": "module" 来使用

import pmutils from '../../lib/pm-utils.es.js' // 测试在es模式 node.js中环境
console.log(pmutils)

关于'es' | 'cjs' | 'umd' | 'iife' 相关介绍

不支持

在package.json中添加

{
    "type": "module" 
}

编译通过

关于'es' | 'cjs' | 'umd' | 'iife' 相关介绍

cjs

CommonJS,只能在 NodeJS 上运行,使用 require("module") 读取并加载模块

每个文件就是一个模块,有自己的作用域。在一个文件里面定义的变量、函数、类,都是私有的,对其他文件不可见

umd

同时兼容 CJS 和 AMD,并且支持直接在前端用 <script src="lib.umd.js"></script> 的方式加载

AMD,全称是Asynchronous Module Definition,即异步模块加载机制

iife

因为我们的应用程序可能包含来自不同源文件的许多函数和全局变量,所以限制全局变量的数量很重要。如果我们有一些不需要再次使用的启动代码,我们可以使用 IIFE 模式。由于我们不会再次重用代码,因此在这种情况下使用 IIFE 比使用函数声明或函数表达式更好

const makeWithdraw = (balance) => ((copyBalance) => {
  let balance = copyBalance; // This variable is private
  const doBadThings = () => {
    console.log('I will do bad things with your money');
  };
  doBadThings();
  return {
    withdraw(amount) {
      if (balance >= amount) {
        balance -= amount;
        return balance;
      }
      return 'Insufficient money';
    },
  };
})(balance);

const firstAccount = makeWithdraw(100);   // "I will do bad things with your money"
console.log(firstAccount.balance);        // undefined
console.log(firstAccount.withdraw(20));   // 80
console.log(firstAccount.withdraw(30));   // 50
console.log(firstAccount.doBadThings);    // undefined; this method is private
const secondAccount = makeWithdraw(20);   // "I will do bad things with your money"
console.log(secondAccount.withdraw(30));  // "Insufficient money"
console.log(secondAccount.withdraw(20));  // 0
版权声明:程序员胖胖胖虎阿 发表于 2022年10月29日 下午9:40。
转载请注明:关于'es' | 'cjs' | 'umd' | 'iife' 相关介绍 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...