From dea7b22cd6adda222e002047ceb3baf579785ee2 Mon Sep 17 00:00:00 2001 From: Norman Breau Date: Tue, 31 Mar 2020 18:48:13 -0300 Subject: [PATCH 1/2] test: GH-178 Unit tests for importing shebang modules --- testLib/sharedTestCases.js | 5 +++++ testLib/shebangModule.js | 7 +++++++ 2 files changed, 12 insertions(+) create mode 100644 testLib/shebangModule.js diff --git a/testLib/sharedTestCases.js b/testLib/sharedTestCases.js index a4158d9..803f59e 100644 --- a/testLib/sharedTestCases.js +++ b/testLib/sharedTestCases.js @@ -408,4 +408,9 @@ module.exports = function () { }).to.throwException(/^Assignment to constant variable at .+?wrongConstModule\.js:4:1$/); }); + it("should be possible to rewire shebang modules", function () { + expect(function () { + rewire("./shebangModule"); + }).to.not.throwError(); + }); }; diff --git a/testLib/shebangModule.js b/testLib/shebangModule.js new file mode 100644 index 0000000..da6ac74 --- /dev/null +++ b/testLib/shebangModule.js @@ -0,0 +1,7 @@ +#!/usr/bin/env node + +function shebangs() { + return true; +} + +module.exports.shebangs = shebangs; From 02440691951cf50003fb6b7eeac2be13981f4c84 Mon Sep 17 00:00:00 2001 From: Norman Breau Date: Tue, 31 Mar 2020 18:48:39 -0300 Subject: [PATCH 2/2] fix: GH-178 import error on shebang modules As of NodeJS 12.16.0, importing modules with shebang declarations failed. This commit checks the first line for shebang declarations and removes them before trying to load the module. --- lib/moduleEnv.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/moduleEnv.js b/lib/moduleEnv.js index 3b05bca..e5bb2e8 100644 --- a/lib/moduleEnv.js +++ b/lib/moduleEnv.js @@ -43,6 +43,8 @@ var moduleWrapper0 = Module.wrapper[0], // errors anyway, it's probably still a reasonable trade-off. // Test the regular expresssion at https://regex101.com/r/dvnZPv/2 and also check out testLib/constModule.js. matchConst = /(^|\s|\}|;)const(\/\*|\s|{)/gm, + // Required for importing modules with shebang declarations, since NodeJS 12.16.0 + shebang = /^(#!).+/, nodeRequire, currentModule; @@ -123,7 +125,9 @@ function jsExtension(module, filename) { _compile.call( module, - content.replace(matchConst, "$1let $2"), // replace const with let, while maintaining the column width + content + .replace(shebang, '') // Remove shebang declarations + .replace(matchConst, "$1let $2"), // replace const with let, while maintaining the column width filename ); };