Skip to content

Instantly share code, notes, and snippets.

@SLaks
Last active December 24, 2015 12:09
Show Gist options
  • Save SLaks/6796178 to your computer and use it in GitHub Desktop.
Save SLaks/6796178 to your computer and use it in GitHub Desktop.
Failed attempts to provide IntelliSense for Node.js in Visual Studio.

This is a failed attempt to make require('./folder/file.js') return the exports object created by that file.

The problem is that the IntelliSense engine runs all imported files before running any user code, so I cannot create a personalized module object for each file separately. Creating a single global module object won't let me figure out what exports come from each module. (If it's possible to pass a parameter to another file, I could solve that)

function require(path) {
if (!/.js(on?)/.test(path))
path += '.js';
// TODO: Get full normalized path to return the same object across files
// TODO: Resolve paths within node_modules folders, and read JSON
// If we've already loaded this module, return the cached exports
if (require.cache.hasOwnProperty(path))
return require.cache[path];
intellisense.logMessage("Preparing to load " + path);
// Create a module global for the remote code to use
var module = window.module = { filename: path };
// Create and cache the module's exports object, even
// if the remote code overwrites module.exports.
require.cache[path] = module.exports = {};
Object.defineProperty(module, 'exports', {
enumerable: true,
get: function () { return require.cache[path]; },
set: function (val) { require.cache[path] = val; }
});
// Load the script so that it will run with its personalized module object
var s = document.createElement('script');
s.src = path;
s.onload = function () {
// This callback never runs
intellisense.logMessage("Loaded " + path);
// TODO: Delete any new globals the script created
};
document.head.appendChild(s);
return require.cache[path];
}
require.cache = {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment