How to config webpack to transpile files from other lerna packages (ejected from create-react-app) How to config webpack to transpile files from other lerna packages (ejected from create-react-app) reactjs reactjs

How to config webpack to transpile files from other lerna packages (ejected from create-react-app)


The bad news: This is a common problem. Create React App doesn't support monorepos, as of ~3.2.0 / late 2019. If you want to share components between lerna sibling packages, many people either avoid using "CRApp", or, include a build script in their component library packages and commit and export pre-transpiled ES5 files.

The good news: I found a fix that seems to work, and doesn't require ejecting CRA. Tested with both local build and test deploy to github pages.

It uses craco, which provides an API for editing CRA's webpack config without ejecting. Craco has plugins which add webpack loaders etc; we'll need craco-babel-loader:

npm i --save @craco/craco craco-babel-loader

...then there are some further CRACO setup steps, check https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation for the latest. At time of writing, you need to replace the following CRA scripts in package.json:

  • react-scripts start => craco start
  • react-scripts build => craco build
  • react-scripts test => craco test

Then we need to create a config file, craco.config.js, in the root of the CRA/craco package that receives ES6+ JSX components from sibling packages, and we need to list the package names to send to babel:

// crago.config.js// see: https://github.com/sharegate/cracoconst path = require('path')const fs = require('fs')const cracoBabelLoader = require('craco-babel-loader')// Handle relative paths to sibling packagesconst appDirectory = fs.realpathSync(process.cwd())const resolvePackage = relativePath => path.resolve(appDirectory, relativePath)module.exports = {  plugins: [    {      plugin: cracoBabelLoader,      options: {        includes: [          // No "unexpected token" error importing components from these lerna siblings:          resolvePackage('../some-component-library'),          resolvePackage('../more-components'),          resolvePackage('../another-components-package'),        ],      },    },  ],}