代码改变世界

pnpm+react-create-app 踩坑记录

2022-07-04 14:24  muamaker  阅读(2570)  评论(0编辑  收藏  举报

一、创建项目

 

 

 

pnpm-workspace.yaml

packages:
  - 'packages/*'

  

package.json

{
  "name": "pnpm-build",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "preinstall": "node ./scripts/preinstall.js",
   
    "start:app": "pnpm --filter @web/my-app  run start "
  },
  "keywords": [],
  "author": "",
  "license": "ISC",

  "engines": {
    "node": ">=10",
    "pnpm": ">=3"
}
}

  

.nvmrc

v16

  

.npmrc

shamefully-hoist=true
strict-peer-dependencies=false

  

scripts/preinstall.js

if (!/pnpm/.test(process.env.npm_execpath || '')) {
    console.warn(
      `\u001b[33mThis repository requires using pnpm as the package manager ` +
        ` for scripts to work properly.\u001b[39m\n`
    )
    process.exit(1)
  }
  
  

  

二、创建 react 项目

在 packages 文件夹下执行

npx react-create-app my-app --template typescript

 

1、创建结束后,删除 node_module

2、cmd 进去packages 外面,执行 pnpm install 

3、执行 pnpm run start:app

 

三、开始踩坑

1、到目前为止,一切正常。

2、开始发挥 pnpm 的 packages 优势,提取公共代码

3、在 packages 下面新建一个 utils 文件夹,新建 package.json

{
"name": "@web/utils"
}

4、并新建 index.ts,随便写点内容

 

 

 

 

5、在 my-app 项目中要引入 utils 里面的代码,需要在外部执行

pnpm --filter @web/my-app i @web/utils -r

  

6、引入代码 

import {loadScript} from  "@web/utils"

  

7、开始报错

 

 

四、解决报错

参考:https://github.com/facebook/create-react-app/issues/1333

1、先 npm run eject

2、config/paths.js 后面加入

module.exports.appPackages = []
// 注意这里 @web 是你当前 package 的前缀 const folderLernaPackageName = '@web' // this is the name of your packages folder in package.json. For example: name: '@my-monorepo/utils' const lernaRoot = path.resolve(module.exports.appPath, '../../') const lernaPackages = path.join(lernaRoot, 'packages') // this is the name of your packages folder in monorepo const regexpFolderLernaPackage = new RegExp(`^${folderLernaPackageName}\\/`, 'g') const lernaPackagesFromDependencies = Object.keys( require(resolveApp('package.json')).dependencies ) .filter((packageName) => packageName.startsWith(folderLernaPackageName)) .map((packageName) => packageName.replace(regexpFolderLernaPackage, '')) fs.readdirSync(lernaPackages).forEach((folderName) => { const isDependencyNeed = lernaPackagesFromDependencies.includes(folderName) if (isDependencyNeed) { module.exports.appPackages.push(path.join(lernaPackages, folderName)) } }); module.exports.appPackages.push(module.exports.appSrc)

  

3、config/webpack.config.js