pnpm: [bug] - Pnpm not working with expo

pnpm version:

6.28.0

Code to reproduce the issue:

expo init pnpm_expo # Choose Typescript tab template
cd pnpm_expo
rm -rf node_modules yarn.lock
pnpm i
pnpm start
# Go to the expo app, and try it

Expected behavior:

Be able to run an expo app without any issue.

Actual behavior:

Error: EISDIR: illegal operation on a directory, read
    at Object.readSync (node:fs:723:3)
    at tryReadSync (node:fs:433:20)
    at Object.readFileSync (node:fs:479:19)
    at UnableToResolveError.buildCodeFrameMessage (/home/olyno/Documents/projects/pnpm_expo/node_modules/.pnpm/metro@0.64.0/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:347:17)
    at new UnableToResolveError (/home/olyno/Documents/projects/pnpm_expo/node_modules/.pnpm/metro@0.64.0/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:333:35)
    at ModuleResolver.resolveDependency (/home/olyno/Documents/projects/pnpm_expo/node_modules/.pnpm/metro@0.64.0/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:211:15)
    at DependencyGraph.resolveDependency (/home/olyno/Documents/projects/pnpm_expo/node_modules/.pnpm/metro@0.64.0/node_modules/metro/src/node-haste/DependencyGraph.js:413:43)
    at /home/olyno/Documents/projects/pnpm_expo/node_modules/.pnpm/metro@0.64.0/node_modules/metro/src/lib/transformHelpers.js:317:42
    at /home/olyno/Documents/projects/pnpm_expo/node_modules/.pnpm/metro@0.64.0/node_modules/metro/src/Server.js:1471:14
    at Generator.next (<anonymous>)
› Stopped server

Additional information:

  • node -v prints: 16.13.2
  • Windows, macOS, or Linux?: Linux, Deepin

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 6
  • Comments: 34 (3 by maintainers)

Commits related to this issue

Most upvoted comments

Hi all! I’ve been investigating making React Native modules more stable for Expo in general. I love the efforts here to make it compatible with pnpm isolated modules, and I honestly think we are nearly there.

Below is a summary of all changes we collectively have made to React Native to support both monorepos and pnpm better. It’s a long read, so here is also a TL;DR;

While @rnx-kit/metro-resolver-symlinks does help change/fix Metro’s resolution, it doesn’t fix the brittleness of monorepos and pnpm isolated modules in React Native. Point 4 of the summary below describes why it’s brittle and can break unexpectedly, and what we intend to do to resolve that.


1. React Native calling into native files, shipped through npm packages.

This is how React Native and all packages are currently structured. They ship both the JS code, as well as the native code or bindings required to run the code. In the past, React Native used hardcoded paths to these packages, which caused a lot of issues in both monorepos and isolated modules, as we can’t expect modules to always be installed in <project>/node_modules/<package>.

This was partially fixed by using Node module resolution from the native layer in: expo/expo#13901.

2. pnpm became more popular but didn’t work with React Native

The initial change from point 1 was intended to improve monorepos better, but not necessarily for pnpm. Unfortunately, the fix still relied on all packages being hoisted to the project or monorepo root node_modules folders.

While this worked for yarn and npm, it didn’t work for pnpm as only direct project dependencies are linked in the project or monorepo root node_modules folders. Transitive dependencies are only linked in the folders that depend on these dependencies. So, instead of just resolving a dependency, we had to resolve the full dependency chain.

This was fixed in expo/expo#24561, and facebook/react-native#36485.

3. Metro still had to support resolving symlinks

While the native layer now properly resolved the packages before accessing them, the JS layer still had to catch up by actually supporting symlinks. Since Metro used something called the haste map (in-memory fs representation), it didn’t work out of the box yet. You can read the full discussion and history in facebook/metro#1 (the first issue 😄).

Because that took its time, Microsoft made their own version of the symlink resolver through RNX Kit. You can use this, but it requires more metro customization.

Luckily, symlink support was added in facebook/metro#ed5545 and recently turned on by default in facebook/metro#9e7cec.

4. Peer dependencies and autolinking conflict in behavior

Since isolated modules only link packages together when either dependencies or peerDependencies are defined, we’d need all packages to have proper dependency chains. Due to historical changes around peerDependencies, Expo has been conservative in defining these constraints. The changes around not installing peer dependencies automatically to actually auto-installing these did break Expo multiple times in the past.

On top of that, React Native doesn’t work this way at all. I would see React Native as a JS runtime that requires native bindings. These native bindings are handled through autolinking, with the constraint that only a single version of each package can be installed per app. Having package managers possibly installing peer dependencies, and thus multiple versions of packages, makes monorepos very brittle for React Native as the JS code of a package can get out-of-sync with the native code of the same but different version of the package. This usually causes the app to crash in various ways, but none of them tell developers that multiple versions are installed (the actual underlying reason it broke).

I’m working on this as we speak. There are quite a few expo—* packages, most of which consume other expo related packages. Right now, we are trying to find a balance between surfacing these conflicts of multiple packages (e.g. multiple react-native versions) and properly resolving these following React Native’s autolinking constraints.

Having more visibility in what’s bundled vs what’s built in your app was also the main reason why Expo released Atlas.

We have a few changes scheduled to be released for SDK 52 that should:

  • Fix the “broken” dependency chains according to isolated modules
  • Modify Expo’s version of Metro to resolve specific packages based on autolinking
  • Surface autolinking conflicts to inform users about possible outdated or broken packages

With these changes, we hope to make pnpm support finally stable for React Native in general.

Hope this helps!

We have a few changes scheduled to be released for SDK 52 that should:

  • Fix the “broken” dependency chains according to isolated modules
  • Modify Expo’s version of Metro to resolve specific packages based on autolinking
  • Surface autolinking conflicts to inform users about possible outdated or broken packages

With these changes, we hope to make pnpm support finally stable for React Native in general.

Hope this helps!

@byCedric still looking forward to this. But I take it this didn’t make it to Expo 52? Any targets we should look out for? Thanks!

I spent the day finding a solution to this problem, and here it is.

It is using rnx-kit to resolve the symlinks, fallback to expos loader for stuff that can’t be resolved, a custom entry for expo, and expo-router, and a custom metro.config.js.

But, no changes to .npmrc.

@zkochan alternatively, if Expo will not do the work above to support symlinks, would pnpm consider adopting into core some public-hoist-pattern[] hoisting exceptions config for Expo and related packages which rely on a fixed node_modules directory structure?

Some users have reported public-hoist-pattern[] configurations working for them:

eg. the following (not tested as working yet)

public-hoist-pattern[]=expo public-hoist-pattern[]=react-native-gradle-plugin public-hoist-pattern[]=@react-native-community/cli-platform-android public-hoist-pattern[]=@react-native-community/cli-platform-ios I know that pnpm already has some public-hoist-pattern[] configuration in core for some other popular packages in the ecosystem which also rely on node_modules directory structure - so I’m asking whether pnpm would also consider this for Expo, if they will not do the work to refactor.

In pnpm v10 we have introduced configurational dependencies. I want to make it possible to install dependencies that can modify pnpm settings. So we’d be able to ship something like an “expo compatibility” package that would automatically configure the correct public-hoist-pattern before installation.

@byCedric now that Expo SDK 50 uses React Native 0.73 (which made the Metro symlinks support stable, which has been reported as working by the community without Expo), would it be considered a bug in Expo for pnpm support to not work out of the box (without node-linker=hoisted or any other workarounds) with a new create-expo app?

The way I understand it, the work involved on Expo’s side for supporting symlinks would be refactoring the following:

  • relative paths from files within node_modules
  • any other code that relies on a fixed node_modules structure

Would be great to be able to use Expo + the new Metro symlink support without the node-linker=hoisted workaround!

@zkochan alternatively, if Expo will not do the work above to support symlinks, would pnpm consider adopting into core some public-hoist-pattern[] hoisting exceptions config for Expo and related packages which rely on a fixed node_modules directory structure?

Some users have reported public-hoist-pattern[] configurations working for them:

eg. the following (not tested as working yet)

public-hoist-pattern[]=*expo*
public-hoist-pattern[]=*react-native-gradle-plugin*
public-hoist-pattern[]=*@react-native-community/cli-platform-android*
public-hoist-pattern[]=*@react-native-community/cli-platform-ios*

I know that pnpm already has some public-hoist-pattern[] configuration in core for some other popular packages in the ecosystem which also rely on node_modules directory structure - so I’m asking whether pnpm would also consider this for Expo, if they will not do the work to refactor.

After wrestling with a pnpm monorepo with an Expo project for 2 days straight I finally made Expo work without using node-linker=hoisted as suggested by https://github.com/pnpm/pnpm/issues/4286#issuecomment-1023521300.

Big shout out to this guide and Microsoft’s rnx-kit. I think going all in and forcing Metro to resolve symlinks was a good idea. I intentionally did not omit additional configuration to show that this Metro config can be extended quite easily while still being easy to read (for your future self).

{
  ...
  "expo": "^51.0.17",
  "expo-router": "~3.5.23",
  "react-native": "^0.74.5",
  ...
}
// Learn more: https://docs.expo.dev/guides/monorepos/
const path = require("path");
const { getDefaultConfig } = require("expo/metro-config");
const { FileStore } = require("metro-cache");
const { withNativeWind } = require("nativewind/metro");
const { makeMetroConfig } = require("@rnx-kit/metro-config");
const { mergeConfig } = require("metro-config");
const MetroSymlinksResolver = require("@rnx-kit/metro-resolver-symlinks");

const symlinksResolver = MetroSymlinksResolver();

const projectDir = __dirname;
const monorepoRoot = path.resolve(projectDir, "../..");
const defaultConfig = getDefaultConfig(projectDir);

/** @type {import('expo/metro-config').MetroConfig} */
const monorepoConfig = {
  resolver: {
    disableHierarchicalLookup: true,
    nodeModulesPaths: [
      path.resolve(projectDir, "node_modules"),
      path.resolve(monorepoRoot, "node_modules"),
    ],
    /**
     * React Native has very frail symlink support for modern monorepo tools  
     * that rely on symlinks and global caches to dramatically increase the
     * performance of installs e.g. pnpm. The best way around this is using
     * Microsoft's rnx-kit. I've written more extensively about this in the
     * README.
     * 
     * @see https://gist.github.com/Zn4rK/ed60c380e7b672e3089074f51792a2b8
     */
    resolveRequest: (context, moduleName, platform) => {
      try {
        // Symlinks resolver throws when it can't find what we're looking for.
        const res = symlinksResolver(context, moduleName, platform);

        if (res) {
          return res;
        }
      } catch {
        /**
         * If we have an error, we pass it on to the next resolver in the chain,
         * which should be one of expos.
         * @see https://github.com/expo/expo/blob/9c025ce7c10b23546ca889f3905f4a46d65608a4/packages/%40expo/cli/src/start/server/metro/withMetroResolvers.ts#L47
         */
        return context.resolveRequest(context, moduleName, platform);
      }
    },
  },
  /**
   * Add the monorepo paths to the Metro config.
   * This allows Metro to resolve modules from the monorepo.
   *
   * @see https://docs.expo.dev/guides/monorepos/#modify-the-metro-config
   */
  watchFolders: [monorepoRoot],
  /**
   * Move the Metro cache to the `node_modules/.cache/metro` folder.
   * This repository configured Turborepo to use this cache location as well.
   * If you have any environment variables, you can configure Turborepo to invalidate it when needed.
   * @see https://turbo.build/repo/docs/reference/configuration#env
   */
  cacheStores: [
    new FileStore({
      root: path.join(projectDir, "node_modules", ".cache", "metro"),
    })
  ]
};

/** @type {import('expo/metro-config').MetroConfig} */
const svgConfig = {
  resolver: {
    assetExts: defaultConfig.resolver.assetExts.filter((ext) => ext !== "svg"),
    sourceExts: [...defaultConfig.resolver.sourceExts, "svg"],
  },
  transformer: {
    // <3 -> https://github.com/kristerkari/react-native-svg-transformer/issues/141
    assetPlugins: ['expo-asset/tools/hashAssetFiles'],
    babelTransformerPath: require.resolve('react-native-svg-transformer/expo'),
  },
};

/**
 * Merging configs do not deeply merge arrays/functions. Keep this in mind to not
 * override important properties. Order matters!
 * 
 * @see https://metrobundler.dev/docs/configuration/#merging-configurations
 */
const finalConfig = makeMetroConfig(mergeConfig(defaultConfig, monorepoConfig, svgConfig));

/**
 * Nativewind config must come last! Internally it uses withCssInterop to 
 * resolve css imports. If this is overridden, Nativewind will not work.
 * 
 * @see https://github.com/nativewind/nativewind/issues/972#issuecomment-2329660147
 *
 * Striking a balance between Nativewind and rnx-kit was tricky
 * 
 * @see https://github.com/nativewind/nativewind/issues/926
 */
module.exports = withNativeWind(finalConfig, {
  input: path.join(projectDir, "./src/global.css"),
  configPath: path.join(projectDir, "./tailwind.config.ts")
});

With this config pnpm monorepos work like a charm. One day we’ll get first class support ❤️

@jwtong

Add node-linker=hoisted in .npmrc file.

https://docs.expo.dev/more/create-expo/#pnpm

@zkochan alternatively, if Expo will not do the work above to support symlinks, would pnpm consider adopting into core some public-hoist-pattern[] hoisting exceptions config for Expo and related packages which rely on a fixed node_modules directory structure?

Some users have reported public-hoist-pattern[] configurations working for them:

eg. the following (not tested as working yet)

public-hoist-pattern[]=*expo*
public-hoist-pattern[]=*react-native-gradle-plugin*
public-hoist-pattern[]=*@react-native-community/cli-platform-android*
public-hoist-pattern[]=*@react-native-community/cli-platform-ios*

I know that pnpm already has some public-hoist-pattern[] configuration in core for some other popular packages in the ecosystem which also rely on node_modules directory structure - so I’m asking whether pnpm would also consider this for Expo, if they will not do the work to refactor.

@byCedric when you get a chance, if you could drop a short comment of which SDK version is expected to contain the pnpm improvements, that would be helpful!

As other users like @jvliwanag have also noted, it appears that the pnpm improvements weren’t shipped in Expo SDK 52:

For the people who like to follow progress, we are rolling out more dependency checks in Expo for all our packages (pr). This is incremental, as we have quite some things to fix.

You can see the list of packages with “unhealthy” dependency chains, meaning it might have issues when using isolated modules. All other packages are actively being monitored through the checks from the PR linked above.

I spent the day finding a solution to this problem, and here it is.

It is using rnx-kit to resolve the symlinks, fallback to expos loader for stuff that can’t be resolved, a custom entry for expo, and expo-router, and a custom metro.config.js.

But, no changes to .npmrc.

@Zn4rK amazing, that sounds great! 👀 🔥

@byCedric @brentvatne what is the Expo team feeling here? Should this be the standard integration with pnpm instead of the current approach with the less-performant .npmrc with node-linker=hoisted?

Also opened an issue in byCedric/expo-monorepo-example to suggest this as a feature:

I’m working in a pnpm monorepo and running the app on iOS worked for me with just shamefully-hoist=true but it would always fail on Android. My fix was adding a custom resolveRequest function to metro.config.js:

config.resolver.resolveRequest = (context, moduleName, platform) => {
  if (
    platform === 'android' &&
    // replace `packages/app` with the path to your app directory in monorepo
    context.originModulePath.endsWith('packages/app/.') &&
    // some weird edge cases, there might be a better way to do this
    !moduleName.startsWith('/') &&
    !moduleName.startsWith('../../') &&
    !moduleName.startsWith('./../../')
  ) {
    // just tell metro to look in the root of the monorepo where pnpm stores all node_modules
    moduleName = `../../${moduleName}`
  }

  // use default
  return context.resolveRequest(context, moduleName, platform)
}

This is a bit hacky but it works great in a pnpm workspaces monorepo with just shamefully-hoist=true (no other npm options needed).

metro.config.js:

const path = require('node:path')

const { getDefaultConfig } = require('expo/metro-config')

const workspaceRoot = path.resolve(__dirname, '../..')
const projectRoot = __dirname

const config = getDefaultConfig(projectRoot)

config.watchFolders = [workspaceRoot]

config.resolver.nodeModulesPaths = [
  path.resolve(projectRoot, 'node_modules'),
  path.resolve(workspaceRoot, 'node_modules'),
]

config.resolver.disableHierarchicalLookup = true
config.resolver.sourceExts.push('cjs')

config.resolver.resolveRequest = (context, moduleName, platform) => {
  if (
    platform === 'android' &&
    // replace `packages/app` with the path to your app directory in monorepo
    context.originModulePath.endsWith('packages/app/.') &&
    // some weird edge cases, there might be a better way to do this
    !moduleName.startsWith('/') &&
    !moduleName.startsWith('../../') &&
    !moduleName.startsWith('./../../')
  ) {
    // just tell metro to look in the root of the monorepo where pnpm stores all node_modules
    moduleName = `../../${moduleName}`
  }

  // use default
  return context.resolveRequest(context, moduleName, platform)
}

module.exports = config

That’s not an issue related to pnpm, or Expo. It’s just how Metro explains it can’t find packages. I got it working with the --shamefully-hoist flag, and going over the steps in Working with Monorepos, in case it helps. https://github.com/byCedric/eas-monorepo-example/pull/19

Thanks. I actually looked into that just now and these are the specific changes necessary for pnpm: https://github.com/rhyek/expo-monorepo-issue/compare/pnpm...pnpm-fixed

It works this way, but isn’t it contrary to the principle of operation of pnpm? The purpose of pnpm is to use symlinks to reduce the size of node_modules, isn’t it?

@wesleyfreit @watadarkstar these two configurations are not following my suggested public-hoist-pattern[]= config above:

  1. Your config above includes Babel, ESLint and Prettier dependencies, which are unrelated to React Native / Expo hoisting problems
  2. Your config above uses node-linker=hoisted, which is a workaround for the issue and avoids the problem which should actually be fixed by Expo / React Native / pnpm (description on option: “A React Native project will most probably only work if you use a hoisted node_modules.”)

The point of issues like this are to try to move past the historical limitation of React Native to not work with symlinks and pnpm’s default isolated linker, now that Expo SDK 50 uses React Native 0.73, which made the Metro symlinks support stable:

Big shout out to this guide and Microsoft’s rnx-kit. With this config pnpm monorepos work like a charm. One day we’ll get first class support ❤️

😂 Yes, I wrote it for this issue specifically: #4286 (comment)

I still found it really tricky to work the symlink resolver into a more complex configuration e.g. svg transform, nativewind etc. Thought it’d be valuable to drop a full working example in this thread.

Big shout out to this guide and Microsoft’s rnx-kit. With this config pnpm monorepos work like a charm. One day we’ll get first class support ❤️

😂 Yes, I wrote it for this issue specifically: https://github.com/pnpm/pnpm/issues/4286#issuecomment-2218470271

@wesleyfreit @watadarkstaressas duas configurações não estão seguindo minha public-hoist-pattern[]=configuração sugerida acima:

  1. Sua configuração acima inclui dependências Babel, ESLint e Prettier, que não estão relacionadas aos problemas de elevação do React Native/Expo
  2. Sua configuração acima usa node-linker=hoisted, que é uma solução alternativa para o problema e evita o problema que deveria ser corrigido pelo Expo / React Native / pnpm (descrição da opção: “Um projeto React Native provavelmente só funcionará se você usar um node_modules elevado.”)

O objetivo de problemas como esse é tentar superar a limitação histórica do React Native de não funcionar com links simbólicos e isolatedo vinculador padrão do pnpm, agora que o Expo SDK 50 usa o React Native 0.73 , o que tornou o suporte a links simbólicos do Metro estável:

The babel package it was the root of the problem in my case, my logs were guided by errors in the babel package. So I used public-hoist-pattern just for it, and my problems disappeared after that configuration I provided above.

Yes, eslint and prettier are not part of this problem, but I was referring in case someone used them, because they have the same problem as babel.

Yes, @karlhorky is correctly, my project is working good using public-hoist-pattern[] pnpm configuration in .npmrc and other configurations in metro.config.js.

I’m using a default expo project created inside the monorepo using turborepo with pnpm.

My .npmrc:

public-hoist-pattern[] = @babel/*
public-hoist-pattern[] = *eslint* // if you use eslint
public-hoist-pattern[] = *prettier* // if you use prettier

In my expo project, I have the @rnx-kit/metro-resolver-symlinks package installed.

And my metro.config.js:

const { getDefaultConfig } = require('expo/metro-config');
const MetroSymlinksResolver = require('@rnx-kit/metro-resolver-symlinks');
const path = require('path');

// Find the workspace root
const workspaceRoot = path.resolve(__dirname, '../..');
const projectRoot = __dirname;

const config = getDefaultConfig(projectRoot);

// Watch all files within the monorepo
config.watchFolders = [workspaceRoot];

// Let Metro know where to resolve packages, and in what order
config.resolver.nodeModulesPaths = [
  path.resolve(projectRoot, 'node_modules'),
  path.resolve(workspaceRoot, 'node_modules'),
];

// Force Metro to resolve (sub)dependencies only from the `nodeModulesPaths`
config.resolver.disableHierarchicalLookup = true;

// Using the Metro Symlinks Resolver config of the `rnx-kit`
config.resolver.resolveRequest = MetroSymlinksResolver();

module.exports = config;

In my project, the typescript path mapping configuration (ex: @/), did not work with the described configuration, so I had to remove it. Maybe I should add another public pattern for typescript, but I preferred not to add it.

Right. But we can’t fix issues in third party libs. The global store is still used. Even with hoisted linker

Try with the node-linker=hoisted option https://pnpm.io/npmrc#node-linker