From 5ccbf387a7c1badc23fd7d0a262fa3db71ad84e8 Mon Sep 17 00:00:00 2001 From: Gray Date: Thu, 10 Jan 2019 13:59:59 +0800 Subject: [PATCH] refactor(jest-support): Replace require.extensions with Module._extensions (#196) --- lib/loader/file_loader.js | 2 +- lib/utils/index.js | 20 +++++++++----------- test/egg-ts.test.js | 4 ++-- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/lib/loader/file_loader.js b/lib/loader/file_loader.js index 0d2abb8f..6d359457 100644 --- a/lib/loader/file_loader.js +++ b/lib/loader/file_loader.js @@ -122,7 +122,7 @@ class FileLoader { parse() { let files = this.options.match; if (!files) { - files = (process.env.EGG_TYPESCRIPT === 'true' && utils.extensions.includes('.ts')) + files = (process.env.EGG_TYPESCRIPT === 'true' && utils.extensions['.ts']) ? [ '**/*.(js|ts)', '!**/*.d.ts' ] : [ '**/*.js' ]; } else { diff --git a/lib/utils/index.js b/lib/utils/index.js index b8268e93..390a65f5 100644 --- a/lib/utils/index.js +++ b/lib/utils/index.js @@ -5,24 +5,22 @@ const is = require('is-type-of'); const path = require('path'); const fs = require('fs'); const co = require('co'); -const extensions = Object.keys(require.extensions); -/* istanbul ignore if */ -if (!extensions.length) { - // adapt for jest - extensions.push('.js', '.node', '.json'); - if (process.env.EGG_TYPESCRIPT === 'true') { - extensions.push('.ts'); - } -} +const BuiltinModule = require('module'); + +// Guard against poorly mocked module constructors. +const Module = module.constructor.length > 1 + ? module.constructor + /* istanbul ignore next */ + : BuiltinModule; module.exports = { - extensions, + extensions: Module._extensions, loadFile(filepath) { try { // if not js module, just return content buffer const extname = path.extname(filepath); - if (extname && !extensions.includes(extname)) { + if (extname && !Module._extensions[extname]) { return fs.readFileSync(filepath); } // require js module diff --git a/test/egg-ts.test.js b/test/egg-ts.test.js index 073bf1cb..500d86db 100644 --- a/test/egg-ts.test.js +++ b/test/egg-ts.test.js @@ -11,13 +11,13 @@ describe('test/egg-ts.test.js', () => { beforeEach(() => { require.extensions['.ts'] = require.extensions['.js']; - loaderUtil.extensions.push('.ts'); + loaderUtil.extensions['.ts'] = require.extensions['.js']; }); afterEach(() => { mm.restore(); - loaderUtil.extensions.splice(loaderUtil.extensions.indexOf('.ts'), 1); delete require.extensions['.ts']; + delete loaderUtil.extensions['.ts']; }); describe('load ts file', () => {