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

Conditional manual import #6

Closed
brillout opened this issue Feb 26, 2023 · 0 comments
Closed

Conditional manual import #6

brillout opened this issue Feb 26, 2023 · 0 comments

Comments

@brillout
Copy link
Owner

brillout commented Feb 26, 2023

If your production and development share the same server entry file, then you need to conditionally import dist/server/entry.js.

There are multiple approaches.


1. Top-level await.

// server.js

if (process.env.NODE_ENV === 'production') {
  await import('./path/to/dist/server/entry.js')
}

// ... server code ...

For environments that don't support top-level await, see alternatives below.


2. Wrap entry code in async function.

// server.js

main()

// We wrap the entire code of server.js in an async function main()
async function main() {
  if (process.env.NODE_ENV === 'production') {
    await import('./path/to/dist/server/entry.js')
  }

  // ... server code ...
}

3. Await import() promise in middleware.

// server.js

const serverBuildPromise = getServerBuildPromise()

app.get('*', async (req, res, next) => {
  // Ensure import('./path/to/dist/server/entry.js') has finished
  await serverBuildPromise()
  // ... middleware ... (e.g. the Vike or Telefunc middleware)
})

function getServerBuildPromise() {
  if (process.env.NODE_ENV !== 'production') return
  let resolve
  const serverBuildPromise = new Promise((r) => { resolve = r })
  import('./path/to/dist/server/entry.js').then(() => {
    resolve()
  })
  return serverBuildPromise
}
@brillout brillout changed the title Conditionally import importBuild.cjs (not in dev but only in prod) Conditional manual import Apr 15, 2023
@brillout brillout closed this as not planned Won't fix, can't repro, duplicate, stale Jun 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant