From d253889d97ff3269b9f07a11731d0ab9a84e1bb9 Mon Sep 17 00:00:00 2001 From: Rob Wu Date: Tue, 15 Aug 2017 12:14:30 +0200 Subject: [PATCH] __non_webpack_require__ -> require in SystemJS When running browser tests, e.g. via `gulp unittest`, the test files are not processed by babel, and neither by the "unittestcli" gulp target. This commit copies the babelPluginReplaceNonWebPackRequire plugin from the unittestcli target to the SystemJS config so that `__non_webpack_require__` is replaced with `require` for all build targets, and adds a unit test to ensure that this indeed works as expected. --- systemjs.config.js | 18 ++++++++++++++++++ test/unit/display_svg_spec.js | 15 +++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/systemjs.config.js b/systemjs.config.js index 9efcf9301..7a4d8df8b 100644 --- a/systemjs.config.js +++ b/systemjs.config.js @@ -39,6 +39,23 @@ typeof crypto !== 'undefined' && typeof crypto.subtle !== 'undefined'; + // When we create a bundle, webpack is run on the source and it will replace + // require with __webpack_require__. When we want to use the real require, + // __non_webpack_require__ has to be used. + // In this target, we don't create a bundle, so we have to replace the + // occurences of __non_webpack_require__ ourselves. + function babelPluginReplaceNonWebPackRequire(babel) { + return { + visitor: { + Identifier(path, state) { + if (path.node.name === '__non_webpack_require__') { + path.replaceWith(babel.types.identifier('require')); + } + }, + }, + }; + } + SystemJS.config({ packages: { '': { @@ -58,6 +75,7 @@ esModule: true, babelOptions: { es2015: false, + plugins: [babelPluginReplaceNonWebPackRequire], }, }, }, diff --git a/test/unit/display_svg_spec.js b/test/unit/display_svg_spec.js index 63821fd06..46f047d11 100644 --- a/test/unit/display_svg_spec.js +++ b/test/unit/display_svg_spec.js @@ -108,6 +108,21 @@ describe('SVGGraphics', function () { }); } + it('should fail require("zlib") unless in Node.js', function() { + function testFunc() { + __non_webpack_require__('zlib'); + } + // Verifies that the script loader replaces __non_webpack_require__ with + // require. + expect(testFunc.toString()).toMatch(/\srequire\(["']zlib["']\)/); + if (isNodeJS()) { + expect(testFunc).not.toThrow(); + } else { + // require not defined, require('zlib') not a module, etc. + expect(testFunc).toThrow(); + } + }); + it('should produce a reasonably small svg:image', function(done) { if (!isNodeJS()) { pending('zlib.deflateSync is not supported in non-Node environments.');