setup-ts-in-node.js (1602B)
1 const path = require('path'); 2 3 // Automatically transpile .ts imports 4 require('ts-node').register({ 5 // Specify the project file so ts-node doesn't try to find it itself based on the CWD. 6 project: path.resolve(__dirname, '../../../tsconfig.json'), 7 compilerOptions: { 8 module: 'commonjs', 9 }, 10 transpileOnly: true, 11 }); 12 const Module = require('module'); 13 14 // Redirect imports of .js files to .ts files 15 const resolveFilename = Module._resolveFilename; 16 Module._resolveFilename = (request, parentModule, isMain) => { 17 do { 18 if (request.startsWith('.') && parentModule.filename.endsWith('.ts')) { 19 // Required for browser (because it needs the actual correct file path and 20 // can't do any kind of file resolution). 21 if (request.endsWith('/index.js')) { 22 throw new Error( 23 "Avoid the name `index.js`; we don't have Node-style path resolution: " + request 24 ); 25 } 26 27 // Import of Node addon modules are valid and should pass through. 28 if (request.endsWith('.node')) { 29 break; 30 } 31 32 if (!request.endsWith('.js')) { 33 throw new Error('All relative imports must end in .js: ' + request); 34 } 35 36 try { 37 const tsRequest = request.substring(0, request.length - '.js'.length) + '.ts'; 38 return resolveFilename.call(this, tsRequest, parentModule, isMain); 39 } catch (ex) { 40 // If the .ts file doesn't exist, try .js instead. 41 break; 42 } 43 } 44 } while (0); 45 46 return resolveFilename.call(this, request, parentModule, isMain); 47 }; 48 49 process.on('unhandledRejection', ex => { 50 throw ex; 51 });