Skip to content

Commit

Permalink
refactor(jest-support): Replace require.extensions with Module._exten…
Browse files Browse the repository at this point in the history
…sions (eggjs#196)
  • Loading branch information
njugray authored and hugh.hyj committed Sep 16, 2021
1 parent cbe056f commit 5ccbf38
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 14 deletions.
2 changes: 1 addition & 1 deletion lib/loader/file_loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
20 changes: 9 additions & 11 deletions lib/utils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions test/egg-ts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 5ccbf38

Please sign in to comment.