Skip to content

Instantly share code, notes, and snippets.

@tomasevich
Created January 22, 2020 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomasevich/d4051e751dac7a0d4f7dc2297cf08262 to your computer and use it in GitHub Desktop.
Save tomasevich/d4051e751dac7a0d4f7dc2297cf08262 to your computer and use it in GitHub Desktop.
Better local require() paths for Node.js

Config

Add this global function to main entrypoint like index.js

global.include = prevPath => {
  const newPath = prevPath.replace('@', __dirname + '/')
  console.log(prevPath, '=>', newPath)

  return require(newPath)
}

Use

const express = require('express') // <- global package
const routes = include('@routes/api') // <- local package

const app = express()

// some stuff...

app.use('/api', routes)

// some stuff...

app.listen(80)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment