Skip to content

Instantly share code, notes, and snippets.

@na2hiro
Last active November 7, 2023 12:52
Show Gist options
  • Select an option

  • Save na2hiro/c3cac13dd4af0532504f652fcc3e0918 to your computer and use it in GitHub Desktop.

Select an option

Save na2hiro/c3cac13dd4af0532504f652fcc3e0918 to your computer and use it in GitHub Desktop.

Revisions

  1. na2hiro revised this gist Nov 7, 2023. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    Main content -> https://github.com/remix-run/remix/discussions/7454#discussioncomment-7498534
  2. na2hiro created this gist Nov 7, 2023.
    36 changes: 36 additions & 0 deletions requireCommon.server.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    import debug from "~/server/debug";

    const d = debug(false)!;

    /**
    * Dynamically require some module. This can be useful to import a module which is initialized in the server entrypoint
    * and you want to import and access it from remix routes. Otherwise, with static imports, Remix would bundle all modules
    * and local variables of module won't be shared
    *
    * One caveat is that we cannot use this in routes directly, otherwise the route will not be defined correctly
    */
    const requireCommon = (moduleName: string) => {
    let module;
    if (__dirname.endsWith("/dist")) {
    // This is /dist/index.js that imports something under app directory.
    // Remix (which uses rollup?) keeps require() as it is in index.js and places the module to under dist/app/..., so we point to the built module here.
    module = moduleName.replace("~/", "./app/");
    d(
    `import ${module} from server bundle at ${__dirname} (originally requiring ${moduleName})`
    );
    } else if (__dirname.endsWith("/sockets")) {
    // Imported from other files under sockets
    module = moduleName.replace("~/sockets/", "./");
    d(
    `import ${module} from sockets at ${__dirname} (originally requiring ${moduleName})`
    );
    } else {
    // Imported from Remix bundle
    module = moduleName.replace("~/", "../dist/app/");
    d(
    `import ${module} from remix bundle at ${__dirname} (originally requiring ${moduleName})`
    );
    }
    return require(module);
    };
    export default requireCommon;