Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vite with SSR: require is not defined #156

Open
omridevk opened this issue Oct 11, 2024 · 16 comments
Open

vite with SSR: require is not defined #156

omridevk opened this issue Oct 11, 2024 · 16 comments
Labels
COMMUNITY: PR is welcomed We think it's a good feature to have but would love for the community to help with the PR for it help wanted Extra attention is needed

Comments

@omridevk
Copy link

omridevk commented Oct 11, 2024

when using SSR, I am getting the following error:

11:02:24 AM [vite] Error when evaluating SSR module /node_modules/__mf__virtual/host_mf_2_page_mf_2_app__loadRemote__remote_mf_1_remote_mf_2_app__loadRemote__.js:
|- ReferenceError: require is not defined

see stackblitz for reproduction:
https://stackblitz.com/edit/github-ad1c93-e4uuvj?file=vite.config.ts,src/main.jsx,test.js

vite config:

import { defineConfig } from 'vite';
import { federation } from '@module-federation/vite';

export default defineConfig({
  ssr: {
    optimizeDeps: {
      include: ['__mf__virtual', '@module-federation/runtime'],
    },
  },
  plugins: [
    federation({
      name: 'host-page-app',
      remotes: {
        remote: {
          type: 'module',
          name: 'remote',
          entry: 'http://test/remoteEntry.js',
          entryGlobalName: 'remote',
          shareScope: 'default',
        },
      },
      filename: 'remoteEntry.js',
    }),
  ],
});

@omridevk
Copy link
Author

run
npm run test
to see the error

@gioboa
Copy link
Collaborator

gioboa commented Oct 11, 2024

Thanks @omridevk for your feedback. We still need to focus into the SSR story, would you like to tackle the problem?

@omridevk
Copy link
Author

sure, it was quite easy to resolve this by using

import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);

and using
default export
instead of the CJS module.exports

@gioboa
Copy link
Collaborator

gioboa commented Oct 11, 2024

@omridevk awesome 👏 I'm looking forward to testing your PR 🚀

@ansbar
Copy link

ansbar commented Oct 14, 2024

@omridevk could you please post a PR or where to use your fix above. We seem to struggle with a simular problem =/

@RobinBomkamp
Copy link
Contributor

We are also facing the same problem in SvelteKit. It was working in version 0.2.8. see #163

@omridevk
Copy link
Author

Yes sorry, had to shift my focus on something else, hopefully will get to this, this week

@veeramarni
Copy link

I couldn't find a workaround for this issue. I'm testing this with Remix app.

@gioboa gioboa added help wanted Extra attention is needed COMMUNITY: PR is welcomed We think it's a good feature to have but would love for the community to help with the PR for it labels Oct 21, 2024
@omridevk
Copy link
Author

@gioboa I was able to get the preview working, but I can't seem to be able to run tests, it is running into some memory issues, i'll add the logs later today

@omridevk
Copy link
Author

virtualRemotes.ts

import VirtualModule from '../utils/VirtualModule';
import { virtualRuntimeInitStatus } from './virtualRuntimeInitStatus';

const cacheRemoteMap: {
  [remote: string]: VirtualModule;
} = {};
export const LOAD_REMOTE_TAG = '__loadRemote__';
export function getRemoteVirtualModule(remote: string, command: string) {
  if (!cacheRemoteMap[remote]) {
    cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, '.js');
    cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
  }
  const virtual = cacheRemoteMap[remote];
  return virtual;
}
const usedRemotesMap: Record<string, Set<string>> = {
  // remote1: {remote1/App, remote1, remote1/Button}
};
export function addUsedRemote(remoteKey: string, remoteModule: string) {
  if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
  usedRemotesMap[remoteKey].add(remoteModule);
}
export function getUsedRemotesMap() {
  return usedRemotesMap;
}
export function generateRemotes(id: string, command: string) {
  return `
    import { createRequire } from 'node:module';
    const require = createRequire(import.meta.url);
    const {loadRemote} = require("@module-federation/runtime")
    const {initPromise} = require("${virtualRuntimeInitStatus.getImportId()}")
    const res = initPromise.then(_ => loadRemote(${JSON.stringify(id)}))
    const exportModule = ${command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await '}initPromise.then(_ => res)
    export default exportModule;
  `;
}

@gioboa
Copy link
Collaborator

gioboa commented Oct 22, 2024

@omridevk nice 👏 great
can you create a PR with your changes please? In this way we can test it in different environments

@Seifenn
Copy link

Seifenn commented Nov 28, 2024

Hello guys is there a develompoent on this issue ? because i have tried @omridevk solution in my app and i dont get the require is not defined message anymore but i'm having problems with the angular dependencies not being loaded. I'm using analog js for SSR wtih angular.

@gioboa
Copy link
Collaborator

gioboa commented Nov 29, 2024

No, there is no progression on this issue. feel free to contribute 😉

@Seifenn
Copy link

Seifenn commented Dec 2, 2024

The package angular-architects/module-federation have added ssr support but their package is not compatible with vite. I'm trying to understand the changes they made and try to reproduce the same approach on this package since i'm having problems with the angular dependecies not exported.

bash ✘ [ERROR] No matching export in "node_modules/__mf__virtual/host_mf_2_app__loadShare___mf_0_angular_mf_1_core__loadShare__.js" for import "Inject" node_modules/@angular/router/fesm2022/router.mjs:8:642: 8 │ ...ctor, ApplicationRef, InjectFlags, APP_INITIALIZER, SkipSelf, NgModule, Inject, Version } from '@angular/core';

I'm not sure of the cause of the error but maybe we can follow the changes they have done to make this module support ssr i'm using analog js as my host for testing ssr and the project can be found on github vite-module-federation-angular-test .

Do you have any suggestions what can be the cause of this error in relation with ssr and module exports ?

@gioboa
Copy link
Collaborator

gioboa commented Dec 18, 2024

I couldn't find a workaround for this issue. I'm testing this with Remix app.

I did this example

It's not working yet because this import from the host is never resolved ( no errors ) 😮‍💨

const Remote = lazy(
  async () => import('remote/remote-app'),
);

Any help is more than welcome.

@RobinBomkamp helped with the SvelteKit example and he added few special edge checks for it here #206
idk if we need to do the same for Remix

@gioboa
Copy link
Collaborator

gioboa commented Dec 19, 2024

@omridevk I tried the basic reproduction repo and I update the dependencies

"@module-federation/vite": "1.2.0",
"vite": "6.0.4"

It's working fine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
COMMUNITY: PR is welcomed We think it's a good feature to have but would love for the community to help with the PR for it help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

6 participants