目前在用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)
不反对
在package.json中增加
{ "type": "module" }
编译通过
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); // undefinedconsole.log(firstAccount.withdraw(20)); // 80console.log(firstAccount.withdraw(30)); // 50console.log(firstAccount.doBadThings); // undefined; this method is privateconst secondAccount = makeWithdraw(20); // "I will do bad things with your money"console.log(secondAccount.withdraw(30)); // "Insufficient money"console.log(secondAccount.withdraw(20)); // 0