Skip to content

Instantly share code, notes, and snippets.

@kapouer
Created August 17, 2020 09:48
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 kapouer/00689d4b36f0cbbe8c514cde1094ce8d to your computer and use it in GitHub Desktop.
Save kapouer/00689d4b36f0cbbe8c514cde1094ce8d to your computer and use it in GitHub Desktop.
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