Main content -> remix-run/remix#7454 (comment)
Last active
November 7, 2023 12:52
-
-
Save na2hiro/c3cac13dd4af0532504f652fcc3e0918 to your computer and use it in GitHub Desktop.
Sharing objects between custom server and Remix code (aka. Use socket.io in Remix) https://github.com/remix-run/remix/discussions/7454#discussioncomment-7498534
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment