What are soft links
Soft links (symlinks) are a very common concept in Linux, but also in Windows, the most common form is probably a shortcut. Creating a soft link does not make a copy of the original file or folder. Instead, it creates a file pointing to the address of the source file. Like an index or pointer. In this way, files can be easily accessed from multiple places and redundant data on hard disks can be reduced.
The application of soft link in development
When we are developing a project, we often use many tools and methods in the code we write, but these tools and methods can be isolated and used as a single lib. In this case, we usually take the form of Monorepo code repository. Take the file structure most commonly used by the open source community as an example:
|-packages
|--pkg1
|---src
|---package.json
|--pkg2
|---src
|---package.json
|-package.json
Copy the code
When pkG1 needs to rely on PKG2 in a project, it is inconvenient to debug using a published file, so you need to link the dependency to a local source file.
Temporary soft link
- Create a link to PKG2 globally
cd pkg2
npm link
Copy the code
cd pkg2
yarn link
Copy the code
- Refer to the pkG2 link in PKG1
cd pkg1
npm link pkg2
Copy the code
cd pkg1
yarn link pkg2
Copy the code
NPM provides an additional command that does not require pkG2 to be linked globally
cd pkg1 npm link .. /pkg2Copy the code
However, the previous two methods do not explicitly declare dependencies on PKG2 in package.json of PKG1. It is inconvenient to re-link dependencies every time you reinstall them. Therefore, NPM and YARN also provide an explicit way to declare dependencies.
Persistent soft link
cd pkg1 npm install .. /pkg2Copy the code
cd pkg1 yarn add file:.. /pkg2Copy the code
Both methods declare dependencies “pkg2”: “file:.. “in the package.json file of pkg1. /pkg2”, but there are some differences. Dependencies installed using NPM exist as soft links in node_modules, whereas YARN creates a hard link to the original file, so changes to PKG2 cannot be fed back to PKG1 in real time during debugging.
You should use YARN to add soft links
cd pkg1 yarn add link:.. /pkg2Copy the code
This gets the same effect as NPM install.. /pkg2 is consistent, but yarn adds declaration dependencies to package.json as “pkg2” : “link:.. /pkg2”, NPM cannot parse this declaration form. Therefore, use NPM and YARN with caution.
Reference documentation
- Docs.npmjs.com/cli/v7/comm…
- Docs.npmjs.com/cli/v7/comm…
- Classic.yarnpkg.com/en/docs/cli…
- Classic.yarnpkg.com/en/docs/cli…