当 yarn 的路径中存在空格时,yarn create 命令报错问题

记录了一个解决 yarn create 命令报错问题的过程。

当 yarn 的路径中存在空格时,yarn create 命令报错问题

今天在一台新 Windows 10 设备上尝试使用 yarn create 命令的时候发现一个报错:

yarn create 报错信息

可以看到是因为我的用户名中存在空格,导致 yarn create 命令误把空格之前的部分当做完整的命令来执行了,这显然是个 Yarn 的 bug。

寻找答案

首先 Google 一下:

google 搜索 yarn create space

很快就能定位到这个 Yarn 项目下的 issue:

cannot run yarn create if yarn is in a folder where the file path has a space · Issue #6851 · yarnpkg/yarn
Yarn v1.12.3 my laptop (helpfully, thank you windows) installed yarn by default in a directory where the file path includes a space (e.g. C:/Users/Some Name/AppData/Yarn...). This results in the fo...

issue 里面有老哥提到了一个比较简单的 workaround。就是重新指定 cache-folderprefix 这两个配置项,将默认路径替换为无空格路径:

yarn config set cache-folder "C:\Users\Valor~1\AppData\Local\Yarn\Cache"
yarn config set prefix "C:\Users\Valor~1\AppData\Local\Yarn"

试了下,搞定!

但过了一会,我居然在 Users 目录下发现了一个名为 Valor~1 的目录。

虽然不行,但还是很好奇老哥是从哪里知道会有 Valor~1 这种短名称的。

继续寻找答案

带着这个疑问继续找答案:

google 搜索 windows shortname

定位到这个提问:

How can I find the short path of a Windows directory/file?
I need to use shortened path names for an application that I am using. For example I need C:\PROGRA~1\ as opposed to C:\Program Files. The program can’t handle spaces and won’t accept quoted paths ...

运行答主 @Paul 在回答里面给出的命令,就可以输出目录缩写了:

dir \x
我的个人目录真正缩写

同时答主 @freedenizen 解释了相关的规则:

The "short name" is really the old DOS 8.3 naming convention, so all the directories will be the first 6 letters followed by ~1 assuming there is only one name that matches, for example:

C:\ABCDEF~1    - C:\ABCDEFG I AM DIRECTORY
C:\BCDEFG~1    - C:\BCDEFGHIJKL I AM ANOTHER DIRECTORY

原来 Windows 对目录的总是保留前 6 个字符,然后以 ~1 结束,如果重复的话,则序号依次递增得到 ~2 ~3 ...

前缀重复时的目录缩写规则
奇怪的知识又增加了

问题解决

显然,对我来讲正确的解决方案应该是:

yarn config set cache-folder "C:\Users\VALORL~1\AppData\Local\Yarn\Cache"
yarn config set prefix "C:\Users\VALORL~1\AppData\Local\Yarn"

运行之后,重新测试,问题解决。


后续阅读了更多的资料之后发现,这个应该是 Node.js 的锅,它居然不支持安装到带空格的路径中。但是别急,我们看下 macOS 的对同样用户名的目录处理方式:

macOS 下我的用户名也是 "Valor Lin"
系统为了更好的兼容性创建的目录名为 "valor.lin"


所以说,归根结底:Windows 就是逊啦~


尝试一下记录问题解决过程的写法,如果大家喜欢这样的文章,给我点赞评论,下次有机会就多写写。

就讲这些了,我们下次再见。