Facebook在今年发布了yarn2.0版本,感觉V2和V1相比还是有一些新的东西加入和很大的改变,尝试着使用了一下yarn V2,做了一个简单的总结;
首先在全局下安装最新的版本
npm install -g yarn@berry
运行
yarn dlx create-react-app my-app
使用react脚手架生成一个项目,由于yarn2.0直接将npn模式内置了,打开项目会发现,没有node_modules文件夹,而是.yarn文件夹和.pnp.js
- .yarn文件夹下cache文件夹里面是放所有依赖的压缩包,zip格式,相对而言压缩了整个项目体积;
- .yarn文件夹下unplugged文件夹是放解压过后的安装包,使用yarn unplug xx 进行解压,解压后的依赖就在这个目录下;
- .pnp.js的主要作用是直接告诉node去哪个目录下查找哪个模块,不需要再按照node_modules之前的查找模式一步步的向上查找,提高了查找效率。
这是yarn V2最大的一个变化,其次还有一个功能相对于开发来说也是一个很好的功能,就是可以通过插件去扩展yarn;
新建一个plugin-hello.js文件,然后再建一个.yarn.yml(yarn2.0的配置文件和锁定文件都更改为纯YAML格式),在.yarn.yml里面写
plugins:
- ./plugin-hello.js
然后在plugin-hello.js里面写插件,这个是yarn官网上给的一个例子,咱直接copy过来尝试一下
module.exports = {
name: `plugin-hello-world`,
factory: require => {
const { Command } = require(`clipanion`);
const yup = require(`yup`);
class HelloWorldCommand extends Command {
async execute() {
this.context.stdout.write(`Hello ${this.email} 💌\n`);
}
}
HelloWorldCommand.addOption(`email`, Command.String(`--email`));
HelloWorldCommand.addPath(`hello`);
HelloWorldCommand.schema = yup.object().shape({
email: yup
.string()
.required()
.email()
});
HelloWorldCommand.usage = Command.Usage({
description: `hello world!`,
details: `
This command will print a nice message.
`,
examples: [
[
`Say hello to an email user`,
`yarn hello --email acidburn@example.com`
]
]
});
return {
commands: [HelloWorldCommand]
};
}
};
然后运行
yarn hello --email xx@163.com
查看输出结果,Hello xx@163.com 💌
yarn2.0还有一些其他的新的特性:
- 增加了两个新的命令(yarn dlx和yarn workspaces foreach);
- 增加了两个新的协议(patch和portal);
- Workspace功能更加强大了;
- 以及刚刚上面提到的锁定文件和配置文件的格式都更改为纯YAML格式;
- 内部使用TypeScript作为开发语言
···
看起来还是挺让人期待的,不过目前目前还是存在一些问题,例如对flow和rn并没有很好的支持,而且相对于yarn1.0的版本来说完全是一个新的东西,如果要是打算迁移的话还是需要慎重考虑一下。