前言
持续系统更新前端工程化相关内容
模块化
模块化规范: CommonJS、ES6、
模块化发展历史
脑图
- commonJS规范
commonJs的模块加载机制是: 输入的值时输出的值的拷贝,也就是说,一点输出了某个值,那么内部这个值不管如何变化,都不会影响到这个值的外部引用。
与之区分的是ES6模块规范, 输入的值时输出的值的引用,也就是说,输入的值时刻受到输出的值的影响
- amd特点
通过工具库RequireJS,利用define将代码定义为模块,利用require加载代码模块
前端模块化的概念已经有很多年的历史了,为什么这几年才开始流行起来呢?是因为tree-shaking是依赖ES6模块化的概念的。
接下俩我们来看一下ES6模块
ES6模块的设计思想是尽可能的静态化,使编译的时候就能确定模块的依赖关系,以及输入输出的变量。然而CommonJS和amd模块规范只能在运行的时候才能确定这些东西,比如commonJs模块就是对象,输入的时候必须查找对象属性
npm
peerDependencies
遇到什么情况的时候我们会想到peerDependencies呢?如下
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.
分析
报错指出了可能是hooks的使用错误或者react依赖版本不一致导致的,react官方也给出了解释:
In order for Hooks to work, the react import from your application code needs to resolve to the same module as the react import from inside the react-dom package.
If these react imports resolve to two different exports objects, you will see this warning. This may happen if you accidentally end up with two copies of the react package.
-
结论 自定义的组件所依赖的react react-dom版本和项目的中版本不一致
-
作用
比如如下的目录结构,3个packageA都需要react依赖
├── helloWorld
│ └── node_modules
│ ├── packageA
│ ├── plugin1
│ │ └── nodule_modules
│ │ └── packageA
│ └── plugin2
│ │ └── nodule_modules
│ │ └── packageA
- helloWorld/package.json
主系统
{
dependencies: {
"packageA": [version]
"react": "^16.13.1",
"react-dom": "^16.13.1"
}
}
- plugin1/package.json
子系统
{
"peerDependecies": {
"packageA": [version]
"react": ">=16.12.0",
"react-dom": ">=16.12.0"
}
}
- plugin2/package.json
子系统
{
"peerDependecies": {
"packageA": [version]
"react": ">=16.12.0",
"react-dom": ">=16.12.0"
}
}
--legacy-peer-deps
NPM v7中,默认安装peerDependencies,但很多情况会有版本冲突问题而中断。--legacy-peer-deps会绕过peerDependencies的自动安装功能。安装各自module下的依赖
npm 常用命令
npm login
npm publish
npm owner add <user> [<@scope>/]<pkg>
npm owner rm <user> [<@scope>/]<pkg>
npm owner ls [<@scope>/]<pkg>
写在后面
- 欢迎关注公众号“燕小书”,回复:“技术交流”进微信技术交流群,公众号会陆续发布优质文章。
- 前端知识库: www.yuque.com/linhao-00ft…