Created
August 17, 2020 09:48
-
-
Save kapouer/00689d4b36f0cbbe8c514cde1094ce8d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const Path = require('path'); | |
/* fix paths before nodejs-like es6 imports | |
* 'root' must be served by statics middleware | |
* 'mount' must be a path prefix to a folder e.g. /modules/ | |
* To allow a node module 'abc' to be served through this, | |
* place a symlink from node_modules/abc to `${root}${mount}abc` | |
* (this is not automatic for security reasons) | |
*/ | |
module.exports = function(root, mount) { | |
if (!mount.startsWith('/') && !mount.endsWith('/')) { | |
throw new Error("Mount must start and end with a slash"); | |
} | |
return async function esm(req, res, next) { | |
if (!req.path.startsWith(mount)) return next(); | |
const lookup = req.path.substring(mount.length); | |
const module = require.resolve(lookup); | |
if (!module) return next(); | |
const path = Path.relative(".", module).replace(/^node_modules\//, mount); | |
req.url = path; | |
next(); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment