Currently using vite to build the project tool library and found some knowledge blind spots
ES
ECMAScript Module, the current module scheme, uses import export to manage dependencies. The browser can use this writing method directly through <script type="module">. NodeJS can be used by using the mjs suffix or adding "type": "module" to package.json
import pmutils from '../../lib/pm-utils.es.js' // 测试在es模式 node.js中环境
console.log(pmutils)
not support
add in package.json
{
"type": "module"
}
Compiled by
cjs
CommonJS, can only run on NodeJS, use require("module") to read and load modules
Each file is a module and has its own scope. Variables, functions, and classes defined in a file are private and invisible to other files
umd
Compatible with both CJS and AMD, and supports loading directly in the front-end with <script src="lib.umd.js"></script>
AMD, the full name is Asynchronous Module Definition, the asynchronous module loading mechanism
iife
Because our application may contain many functions and global variables from different source files, it is important to limit the number of global variables. If we have some startup code that doesn't need to be used again, we can use IIFE mode. Since we won't reuse the code again, it's better to use an IIFE in this case than a function declaration or function expression
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
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。