Skip to content

Instantly share code, notes, and snippets.

@ilfroloff
Last active January 25, 2017 11:25
Show Gist options
  • Save ilfroloff/283761d53d8cbafeb255470cd4106979 to your computer and use it in GitHub Desktop.
Save ilfroloff/283761d53d8cbafeb255470cd4106979 to your computer and use it in GitHub Desktop.
Wrap you Node.js project code by "use strict"

##What is

Redefine global module with "use strict" wrapper for own code. This module doesn't touch node_modules code, because node_modules can be didn't compatibilite with "use strict" requirements

How to test:

node start_point.js

it show in console appear "It works!" (this message prints by my_own_code.js file)

But if invoke:

node my_own_code.js

it throw error

(function (exports, require, module, __filename, __dirname) { class ItWorks {
                                                              ^^^^^
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
class ItWorks {
static log() {
console.log('It works!');
}
}
ItWorks.log();
"use strict";
require('./use_strict_wrapper')(__dirname);
require('./my_own_code');
"use strict";
const Module = require("module");
module.exports = function(project_folder) {
Module.originalWrap = Module.wrap;
Module.wrapWithUseStrict = function(script) {
return this.originalWrap(`"use strict";${script}`);
};
Module.prototype.originalLoad = Module.prototype.load;
Module.prototype.load = function(filename) {
const Module = this.constructor;
Module.wrap = filename.indexOf(project_folder) !== -1 && filename.indexOf('node_modules') === -1?
Module.wrapWithUseStrict :
Module.originalWrap;
return this.originalLoad(filename);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment