Unable to use alias Preact in `next` branch

Author: birtlesCreated Sep 14, 2023Updated Oct 9, 2024

What's wrong?

I'm trying to set up react-cosmos@next on a project using Preact but I get include errors due to some files including react:

$ cosmos
node:internal/errors:490
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'react' imported from C:\Users\Brian\10ten-ja-reader\node_modules\react-cosmos-core\dist\\\utils\react\ClassStateMock.js
    at new NodeError (node:internal/errors:399:5)
    at packageResolve (node:internal/modules/esm/resolve:889:9)
    at moduleResolve (node:internal/modules/esm/resolve:938:20)
    at defaultResolve (node:internal/modules/esm/resolve:1153:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

Node.js v18.16.0

I've tried adding a separate webpack config for cosmos like the following but, as far as I can tell, the error occurs before that is applied:

javascript
return {
  resolve: {
    alias: {
      react: 'preact/compat',
      'react-dom/test-utils': 'preact/test-utils',
      'react-dom': 'preact/compat',
    },
    extensions: ['.ts', '.tsx', '.js'],
  },
};

Steps to reproduce

Sorry, it's going to take me a while to reduce this. But it should be possible to reproduce on any existing project by removing react from the project's dependencies and installing preact instead, then aliasing it in webpack config as shown above.

Useful info

  • Cosmos version: react-cosmos@next
  • Cosmos config
{
  "$schema": "http://json.schemastore.org/cosmos-config",
  "plugins": ["react-cosmos-plugin-webpack"],
  "webpack": {
    "configPath": "./cosmos-webpack.config.js"
  }
}
  • Server terminal output (see above)
  • Browser console output (n/a)

Additional context

This used to work after I fixed it in #1316.

Source: react-cosmos/react-cosmos