@@ -23,6 +23,48 @@ var originalJsHandler = require.extensions['.js']
2323
2424var extHandlers = { }
2525
26+ function hasOwnProperty ( object , property ) {
27+ return Object . prototype . hasOwnProperty . call ( object , property )
28+ }
29+
30+ function getCwd ( dir , scriptMode , scriptPath ) {
31+ if ( scriptMode ) {
32+ if ( ! scriptPath ) {
33+ throw new TypeError ( 'Script mode must be used with a script name, e.g. `ts-node-dev -s <script.ts>`' )
34+ }
35+
36+ if ( dir ) {
37+ throw new TypeError ( 'Script mode cannot be combined with `--dir`' )
38+ }
39+
40+ // Use node's own resolution behavior to ensure we follow symlinks.
41+ // scriptPath may omit file extension or point to a directory with or without package.json.
42+ // This happens before we are registered, so we tell node's resolver to consider ts, tsx, and jsx files.
43+ // In extremely rare cases, is is technically possible to resolve the wrong directory,
44+ // because we do not yet know preferTsExts, jsx, nor allowJs.
45+ // See also, justification why this will not happen in real-world situations:
46+ // https://github.com/TypeStrong/ts-node/pull/1009#issuecomment-613017081
47+ const exts = [ '.js' , '.jsx' , '.ts' , '.tsx' ]
48+ const extsTemporarilyInstalled = [ ]
49+ for ( const ext of exts ) {
50+ if ( ! hasOwnProperty ( require . extensions , ext ) ) { // tslint:disable-line
51+ extsTemporarilyInstalled . push ( ext )
52+ require . extensions [ ext ] = function ( ) { } // tslint:disable-line
53+ }
54+ }
55+ try {
56+ return path . dirname ( require . resolve ( scriptPath ) )
57+ } finally {
58+ for ( const ext of extsTemporarilyInstalled ) {
59+ delete require . extensions [ ext ] // tslint:disable-line
60+ }
61+ }
62+ }
63+
64+ return dir
65+ }
66+
67+
2668var compiler = {
2769 allowJs : false ,
2870 tsConfigPath : '' ,
@@ -196,12 +238,14 @@ var compiler = {
196238 ignore = [ ignore ]
197239 }
198240
241+ const scriptPath = options . _ . length ? path . resolve ( cwd , options . _ [ 0 ] ) : undefined
242+
199243 var DEFAULTS = tsNode . DEFAULTS
200244
201245 try {
202246 compiler . service = tsNode . register ( {
203- // should add -- script-mode
204- dir : options [ 'dir' ] || DEFAULTS . dir ,
247+ // --dir does not work (it gives a boolean only) so we only check for script-mode
248+ dir : getCwd ( options [ 'dir' ] , options [ 'script-mode' ] , scriptPath ) ,
205249 scope : options [ 'dir' ] || DEFAULTS . scope ,
206250 emit : options [ 'emit' ] || DEFAULTS . emit ,
207251 files : options [ 'files' ] || DEFAULTS . files ,
0 commit comments