This article participated in the weekly source code reading activity initiated by the public account @ Ruo Chuan Vision , click for details to participate together.
[Wakagawa Vision x Source Code Reading] Issue 36 | Probably the simplest issue in history omit.js removes attributes from objects Click to learn more about this issue and participate together .
foreword
All the code for the practice in this article has been uploaded, the source code address: github.com/aehyok/omit…
From different perspectives, to learn source code knowledge, through this article, you can learn the following knowledge:
1、准备源代码
2、了解package.json依赖
3、omit方法解析
4、将原来的单元测试修改为jest
5、让项目支持typescript
6、npm publish实践
7、总结
复制代码
1. Prepare the source code
// 浏览器打开源码地址
https://github.com/benjycui/omit.js
//点击`fork`,复制一份代码到自己的仓库
git clone [email protected]:aehyok/omit.js.git
//通过vscode打开项目后,安装依赖
npm i
// 安装完依赖后,执行测试用例
npm run test
复制代码
One test set, two test methods can be found.
2. View dependencies in package.json
2.1, father dependency package
Unexpectedly, it belongs to the umijs family. It has such powerful functions. I won't go into details. Just look at the description on the official website below.
2.2, @umijs/fabric dependency package
Also in the umjjs family
After reading its official documentation, after installing dependencies, it contains the basic configuration of eslint, prettier, and stylelint.
After reading the configuration here require.resolve
, this idea is also very good by loading the packaged configuration.
Here I just learned how . It is here by encapsulating and then running the instructions to directly eslint和prettier
generate the configuration file in the project. And @umijs/fabric
here is the configuration file that references the package.
The collision of the two ideas, no one is better than the other, just talking about the applicability of the scene, for my study, there is another idea. Then I took a look at the source code of **@umijs/fabric**. I looked a little confused, but I still understood the general logic. If you have time, you can fish it when you have time.
2.3、assert
原来这也是一个写单元测试的npm包,周下载量为10,421,399,github上的star274
我顺手查了一下jest的周下载量,16,359,268,但github上的star却达到了39,5k
,大趋势来说还是要用jest,毕竟功能更强大。但是一些比较老的项目,确实都使用了assert
,比如lodash
,大部分前端应该都熟悉或者使用很广泛的一个npm库。
2.4、np
A better
npm publish
通过官网的第一句便可以看出来,这个np
对于发包,也就是发布到npmjs上,非常有用的一个工具。
2.5、 prepublishOnly
scripts
中的一个指令,在npm publish
命令前执行
"compile": "father build",
"prepublishOnly": "npm run compile && np --yolo --no-publish",
复制代码
3、查看omit方法
function omit(obj, fields) {
// eslint-disable-next-line prefer-object-spread
const shallowCopy = Object.assign({}, obj);
for (let i = 0; i < fields.length; i += 1) {
const key = fields[i];
delete shallowCopy[key];
}
return shallowCopy;
}
export default omit;
复制代码
其中Object.assign()
方法用于对象的合并,将源对象(source)的所有可枚举属性,复制到目标对象(target)。
通过Object.assign
浅拷贝一份对象,因为源对象用了一个{}
空的对象。然后对循环传入的fileds
数组,将存在于对象上的key进行移除,这样移除的时候不会对传入的obj对象产生影响。 但是这里单层的循环,对于嵌套的对象就不起作用了。
同时你也可以去查看lodash,也有同样的方法,链接地址 www.lodashjs.com/docs/lodash…
4、jest重写测试用例
- 安装依赖
npm i jest -D
复制代码
- 添加jest.config.js配置文件
npx jest --init
复制代码
然后根据选择提示进行如下选择
执行完成后,在根目录下生成了jest.config.js文件。 以及重写了package.json
中的scripts
"test": "jest",
// 之前是
father test
复制代码
现在可以执行一下命令npm run test
,发现报错了,如下图所示
这里主要是因为我没有配置babel
进行转换,可以通过如下命令进行安装并配置
npm i babel-jest @babel/core @babel/preset-env -D
复制代码
安装完毕后,在根目录配置好babel.config.js
// babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current', //针对当前node版本进行编译,删除该行可能导致`npm start`报错
},
},
],
],
};
复制代码
配置完毕后,再次运行命令npm run test
,执行成功
将assert改为jest的方法
// import assert from 'assert';
import omit from '../src';
describe('omit', () => {
it('should create a shallow copy', () => {
const benjy = { name: 'Benjy' };
const copy = omit(benjy, []);
expect(copy).toEqual(benjy)
});
it('should drop fields which are passed in', () => {
const benjy = { name: 'Benjy', age: 18 };
const target1 = omit(benjy, ['age'])
const target2 = omit(benjy, ['age', 'name'])
expect(target1).toEqual({ name: "Benjy"})
expect(target2).toEqual({})
});
});
复制代码
主要就是将原来的assert
改为了jest
。
2.3、新增一个方法 在src/index.js添加一个求和方法
export const sum = (x, y) => {
return x + y;
}
复制代码
然后在测试用例文件中添加单元测试
import omit, { sum } from '../src';
describe('sum', () => {
it('两数字之和', () => {
expect(sum(3,4)).toEqual(7)
})
})
复制代码
最后通过命令检测单元测试npm run test
通过修改jest.config.js,还可以查看到单元测试覆盖率,看一下效果
collectCoverage: true,
coverageDirectory: "coverage",
复制代码
同时也会生成一个文件coverage
5、支持TypeScript改写
安装typescript依赖
npm i -D typescript
复制代码
安装tsc,并初始化typescript配置
npx tsc --init
复制代码
执行完毕后,在根目录下会生成tsconfig.json
再来安装ts-jest
npm i -D ts-jest
复制代码
在jest.config.js
中添加一行配置
module.exports = {
preset: 'ts-jest',
// ...
};
复制代码
现在可以将src,以及test文件夹下的index.js文件名修改为index.ts文件
src下的文件同时要修改文件中的方法,来支持ts类型的支持
function omit(obj: Object, fields: string[]) {
// eslint-disable-next-line prefer-object-spread
const shallowCopy: any = Object.assign({}, obj);
for (let i = 0; i < fields.length; i += 1) {
const key = fields[i];
delete shallowCopy[key];
}
return shallowCopy;
}
export const sum = (x: number, y: number) => {
return x + y;
};
export default omit;
复制代码
查看测试文件后有报错
此时需要安装ts的jest type 的支持
npm i -D @types/jest
复制代码
安装完毕后,执行npm run test
ts文件的测试用例执行成功,说明typescript配置生效了。
7、发布到npm
- 修改package.json中的name,防止跟原作者冲突了
"name": "aehyok.omit.js",
复制代码
-
npmjs注册账号 记得还要设置邮箱,登录和发布时都需要
-
npm login 或者npm adduser
-
npm publish
- 查看npmjs
8、总结
-
了解Object.assign用法,以及浅克隆,还可以去了解实践一下浅克隆和深克隆
-
npm内置指令 prepublishOnly,发布之前执行的
-
omit方法学习
-
修改源码支持jest单元测试
-
修改源码支持typescript
-
实践npm publish
本文实践所有代码已上传,源码地址:github.com/aehyok/omit…
I am participating in the recruitment of the creator signing program of the Nuggets Technology Community, click the link to register and submit .