Skip to content

Instantly share code, notes, and snippets.

@carlevans719
Created January 4, 2018 10:51
Show Gist options
  • Save carlevans719/12da9f5e11d0a2e65f400017aea72e2c to your computer and use it in GitHub Desktop.
Save carlevans719/12da9f5e11d0a2e65f400017aea72e2c to your computer and use it in GitHub Desktop.
Conditional import/export based on locus in Meteor with typings
// these imports exist only in typescript-land (just importing types)
import * as _serverExports from './index.server'
import * as _clientExports from './index.client'
// Meteor for isClient / isServer
import { Meteor } from 'meteor/meteor'
// isomorphic imports
import { findByEmail } from './findByEmail'
// define vars with the same name as the client / server exports
// more importantly, copy over the original functions' typedefs
// so even though these vars are `undefined` at runtime, TS will
// tell you that they're `(blah, blah, blah) => something` (or w/e)
let {runCreationHooks, registerAccountCreationHook} = {} as typeof _serverExports
let {findByQuery, findByUsername} = {} as typeof _clientExports
if (Meteor.isServer) {
// here's the sexy bit, import the _actual_ server exports (note how we're nested here)
const serverExports: typeof _serverExports = require('./index.server')
// overwrite the `undefined` values with the real things
runCreationHooks = serverExports.runCreationHooks
registerAccountCreationHook = serverExports.registerAccountCreationHook
// ...
}
if (Meteor.isClient) {
// same thing for client-only exports
const clientExports: typeof _clientExports = require('./index.client')
findByQuery = clientExports.findByQuery
findByUsername = clientExports.findByUsername
// ...
}
// export everything - important because TS and IDEs don't handle
// nested imports/exports *or* conditional imports/exports well.
// note that some of these values will be `undefined` depending on
// the current environment
export {
findByEmail,
runCreationHooks,
registerAccountCreationHook,
findByQuery,
findByUsername
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment