Monorepo

GitbookCourses2021-02-16


🪕 Monorepo

A monorepo (mono repository) is a single repository that stores all of your code and assets for every project. It makes it easier to share code. It even makes it easier to refactor code.

  • 🐉 Lerna — The Monorepo manager
  • 📦 Yarn Workspaces — Sane multi-package management
  • 🚀 React — JavaScript library for user interfaces
  • 💅 styled-components — CSS in JS elegance
  • 🛠 Babel — Compiles next-gen JavaScript
  • 📖 Storybook— UI Component Environment
  • 🃏 Jest — Unit/Snapshot Testing

📑 mocha configurate

  • install mocha, eslint-plugin-mocha
  • config in .eslintrc.json:

    "env": {
    "mocha": true
    },
    "extends": ["plugin:mocha/recommended"],
  • better in test folder

    mocha test/**/*.js --watch

📑 jest


  • install jest, eslint-plugin-jest
  • config:

    "env": {
      "jest": true
    },
    "extends": ["plugin:jest/recommended"],

📑 lerna - versioning


  • command:

    $ lerna init
    $ lerna publish
    $ lerna diff [package?]
    $ lerna changed
    $ lerna run --scope [<packages>] [script]
    $ lerna bootstrap --hoist
    $ lerna publish
  • lerna.json:

    {
    	"packages": ["packages/*"],
    	"npmClient": "yarn",
    	"useWorkspaces": true,
    	"version": "0.0.0"
    }
  • ecosystem: babeljs, create-react-app, react-router, jest, graphql, express-generator
  • for linting, unit/functional/performance testing you can combine them with lerna to easily run these commands across packages.

📑 yarn workspaces


  • package.json:

    {
    	"private": true,
    	"workspaces": {
    		"packages": ["packages/*"],
    		"nohoist": ["..."]
    	},
    	"license": "MIT"
    }
  • ecosystem: gatsby

📑 more monorepo tools


  • rush
  • pnpm workspaces
  • One Source of Truth:

    • eslint rules
    • typescript config
    • test setup
    • storybook and more addons
  • reference: github.com/michaljach/modern-monorepo-boilerplate
  • berry, yarn 2

    monorepo 模式与隐式依赖


在 monorepo 模式中,无论是 lerna 还是 yarn 工作机制的核心都是:

将所有 package 的依赖都尽量以 flat 模式安装到根级别的 nodemodules 里,即 hoist,以避免各个 package 重复安装第三方依赖;将有冲突的依赖,安装在各自 package 的 nodemodules 里,以解决依赖的版本冲突问题。 将各个 package 都软链到根级别的 nodemodules 里,这样各个 package 利用 Node 的递归查找机制,可以导入其他 package,不需要自己进行手动的 link。 将各个 package 里 nodemodules 的 bin 软链到 root level 的 node_modules 里,保证每个 package 的 npm script 能正常运行。