react-cosmos: Unable to use alias Preact in `next` branch

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:

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.

About this issue

  • Original URL
  • State: open
  • Created 3 years ago
  • Comments: 15 (14 by maintainers)

Most upvoted comments

The module-based approach seems to work fine so I’ll stick with that. It basically boils down to:

  1. Add a file, e.g. cosmos-policy.json
{
  "dependencies": true,
  "scopes": {
    "": {
      "cascade": true,
      "integrity": true,
      "dependencies": {
        "react": "./node_modules/preact/compat/dist/compat.mjs"
      }
    }
  }
}
  1. Update package.json to include:
{
  "scripts": {
    "cosmos": "node --experimental-policy=cosmos-policy.json node_modules/react-cosmos/bin/cosmos.js",
    "cosmos-export": "node --experimental-policy=cosmos-policy.json node_modules/react-cosmos/bin/cosmos-export.js"
  }
}

Also, I debugged why react-cosmos-plugin-webpack wasn’t handling my webpack.config.js and it appears to be because it doesn’t handle multiple configurations.