Skip to content

Commit 08fc620

Browse files
committed
fix js/ts extension handling
1 parent 4e97863 commit 08fc620

File tree

4 files changed

+68
-42
lines changed

4 files changed

+68
-42
lines changed

lib/child-require-hook.js

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,18 @@ function registerExtensions(extensions) {
6262
return old(m, fileName)
6363
}
6464
})
65+
if (preferTs) {
66+
function reorderRequireExtension (ext) {
67+
var old = require.extensions[ext]
68+
delete require.extensions[ext]
69+
require.extensions[ext] = old
70+
}
71+
var order = ['.ts'].concat(Object.keys(require.extensions)
72+
.filter(_ => _ !== '.ts'))
73+
order.forEach(function (ext) {
74+
reorderRequireExtension(ext)
75+
})
76+
}
6577
}
6678

6779
function isFileInNodeModules(fileName) {
@@ -70,19 +82,20 @@ function isFileInNodeModules(fileName) {
7082

7183
function registerJsExtension() {
7284
var old = require.extensions['.js']
85+
// handling preferTs probably redundant after reordering
7386
if (allowJs || preferTs) {
7487
require.extensions['.js'] = function(m, fileName) {
7588
if (fileName.indexOf(libPath) === 0) {
7689
return old(m, fileName)
77-
}
90+
}
7891
var tsCode
7992
var tsFileName
80-
if (preferTs && !isFileInNodeModules(fileName)) {
81-
tsFileName = fileName.replace(/\.js$/, '.ts')
82-
if (fs.existsSync(tsFileName)) {
83-
tsCode = fs.readFileSync(tsFileName, 'utf-8')
84-
}
85-
}
93+
// if (preferTs && !isFileInNodeModules(fileName)) {
94+
// tsFileName = fileName.replace(/\.js$/, '.ts')
95+
// // if (fs.existsSync(tsFileName)) {
96+
// // tsCode = fs.readFileSync(tsFileName, 'utf-8')
97+
// // }
98+
// }
8699
var _compile = m._compile
87100
var isIgnored =
88101
ignore &&
@@ -99,6 +112,7 @@ function registerJsExtension() {
99112
return _compile.call(this, compile(code, fileName), fileName)
100113
}
101114
}
115+
102116
return old(m, fileName)
103117
}
104118
}

lib/compiler.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,9 @@ var compiler = {
138138
tmpDir = options['cache-directory']
139139
? path.resolve(options['cache-directory'])
140140
: fs.mkdtempSync(path.join(os.tmpdir(), '.ts-node'))
141-
141+
142142
compiler.registerTsNode()
143-
143+
144144
/* clean up compiled on each new init*/
145145
rimraf.sync(compiler.getCompiledDir())
146146
compiler.createCompiledDir()
@@ -152,7 +152,7 @@ var compiler = {
152152
extensions.push('.js')
153153
}
154154

155-
compiler.writeChildHookFile(options)
155+
compiler.writeChildHookFile(options)
156156
},
157157
registerTsNode: function () {
158158
var options = compiler.options

lib/index.js

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ var tsVersion = require('typescript').version
99
var kill = require('tree-kill')
1010
var readline = require('readline')
1111

12-
module.exports = function(script, scriptArgs, nodeArgs, opts) {
12+
13+
module.exports = function (script, scriptArgs, nodeArgs, opts) {
1314
if (typeof script !== 'string' || script.length === 0) {
1415
throw new TypeError('`script` must be a string')
1516
}
@@ -44,35 +45,37 @@ module.exports = function(script, scriptArgs, nodeArgs, opts) {
4445
// debounce: parseInt(opts.debounce),
4546
// recursive: process.platform !== 'linux'
4647
// })
47-
48-
function initWatcher () {
48+
49+
function initWatcher() {
4950
var watcher = chokidar.watch([], {
5051
usePolling: opts.poll,
5152
interval: parseInt(opts.interval) || undefined,
52-
5353
})
5454
watcher.on('change', restart)
5555

56-
watcher.on('fallback', function(limit) {
57-
log.warn('node-dev ran out of file handles after watching %s files.', limit)
56+
watcher.on('fallback', function (limit) {
57+
log.warn(
58+
'node-dev ran out of file handles after watching %s files.',
59+
limit
60+
)
5861
log.warn('Falling back to polling which uses more CPU.')
5962
log.info('Run ulimit -n 10000 to increase the file descriptor limit.')
6063
if (cfg.deps) log.info('... or add `--no-deps` to use less file handles.')
6164
})
6265
return watcher
6366
}
6467
var watcher = initWatcher()
65-
68+
6669
var starting = false
67-
70+
6871
// Read for "rs" from command line
6972
if (opts.rs !== false) {
7073
const rl = readline.createInterface({
7174
input: process.stdin,
7275
output: process.stdout,
73-
terminal: false
76+
terminal: false,
7477
})
75-
rl.on('line', function(line) {
78+
rl.on('line', function (line) {
7679
if (line.trim() === 'rs') {
7780
restart('', true)
7881
}
@@ -99,22 +102,22 @@ module.exports = function(script, scriptArgs, nodeArgs, opts) {
99102
log.debug('Starting child process %s', cmd.join(' '))
100103
child = fork(cmd[0], cmd.slice(1), {
101104
cwd: process.cwd(),
102-
env: process.env
105+
env: process.env,
103106
})
104107
starting = false
105108
//var compileReqWatcher = filewatcher({ forcePolling: opts.poll })
106109
if (compileReqWatcher) {
107110
compileReqWatcher.close()
108-
}
111+
}
109112
compileReqWatcher = chokidar.watch([], {
110113
usePolling: opts.poll,
111-
interval: parseInt(opts.interval) || undefined
114+
interval: parseInt(opts.interval) || undefined,
112115
})
113116
var currentCompilePath
114117
fs.writeFileSync(compiler.getCompileReqFilePath(), '')
115118
compileReqWatcher.add(compiler.getCompileReqFilePath())
116-
compileReqWatcher.on('change', function(file) {
117-
fs.readFile(file, 'utf-8', function(err, data) {
119+
compileReqWatcher.on('change', function (file) {
120+
fs.readFile(file, 'utf-8', function (err, data) {
118121
if (err) {
119122
log.error('Error reading compile request file', err)
120123
return
@@ -128,19 +131,19 @@ module.exports = function(script, scriptArgs, nodeArgs, opts) {
128131
if (compiledPath) {
129132
compiler.compile({
130133
compile: compile,
131-
compiledPath: compiledPath
134+
compiledPath: compiledPath,
132135
})
133136
}
134137
})
135138
})
136-
child.on('message', function(message) {
139+
child.on('message', function (message) {
137140
if (!message.compiledPath || currentCompilePath === message.compiledPath)
138141
return
139142
currentCompilePath = message.compiledPath
140143
compiler.compile(message)
141144
})
142145

143-
child.on('exit', function(code) {
146+
child.on('exit', function (code) {
144147
log.debug('Child exited with code %s', code)
145148
if (!child) return
146149
if (!child.respawn) process.exit(code)
@@ -156,18 +159,19 @@ module.exports = function(script, scriptArgs, nodeArgs, opts) {
156159
}
157160

158161
// Listen for `required` messages and watch the required file.
159-
ipc.on(child, 'required', function(m) {
162+
ipc.on(child, 'required', function (m) {
160163
var isIgnored =
161164
cfg.ignore.some(isPrefixOf(m.required)) ||
162165
cfg.ignore.some(isRegExpMatch(m.required))
163166

164167
if (!isIgnored && (cfg.deps === -1 || getLevel(m.required) <= cfg.deps)) {
168+
log.debug(m.required, 'added to watcher')
165169
watcher.add(m.required)
166170
}
167171
})
168172

169173
// Upon errors, display a notification and tell the child to exit.
170-
ipc.on(child, 'error', function(m) {
174+
ipc.on(child, 'error', function (m) {
171175
log.debug('Child error')
172176
notify(m.error, m.message, 'error')
173177
stop(m.willTerminate)
@@ -194,7 +198,7 @@ module.exports = function(script, scriptArgs, nodeArgs, opts) {
194198
log.debug('Disconnecting from child')
195199
child.disconnect()
196200
//if (!willTerminate) {
197-
killChild()
201+
killChild()
198202
//}
199203
}
200204
}
@@ -219,7 +223,7 @@ module.exports = function(script, scriptArgs, nodeArgs, opts) {
219223
}
220224
log.debug('Removing all watchers from files')
221225
//watcher.removeAll()ya
222-
226+
223227
watcher.close()
224228
watcher = initWatcher()
225229
starting = true
@@ -235,18 +239,18 @@ module.exports = function(script, scriptArgs, nodeArgs, opts) {
235239
compiler.restart = restart
236240

237241
// Relay SIGTERM
238-
process.on('SIGTERM', function() {
242+
process.on('SIGTERM', function () {
239243
log.debug('Process got SIGTERM')
240244
killChild()
241245
if (opts['restart-terminated']) {
242246
var timeout = opts['restart-terminated'] || 0
243247
log.info('Restarting terminated in ' + timeout + ' seconds')
244-
setTimeout(() => {
248+
setTimeout(() => {
245249
start()
246250
}, timeout)
247251
} else {
248252
process.exit(0)
249-
}
253+
}
250254
})
251255

252256
start()
@@ -273,13 +277,13 @@ function getPrefix(mod) {
273277
}
274278

275279
function isPrefixOf(value) {
276-
return function(prefix) {
280+
return function (prefix) {
277281
return value.indexOf(prefix) === 0
278282
}
279283
}
280284

281285
function isRegExpMatch(value) {
282-
return function(regExp) {
286+
return function (regExp) {
283287
return new RegExp(regExp).test(value)
284288
}
285289
}

test/index.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -190,15 +190,15 @@ test('It allows to use custom TS Transformers', async (t) => {
190190
await ps.exit()
191191
})
192192
//
193-
test.only('It should --prefer-ts', async (t) => {
193+
test('It should --prefer-ts', async (t) => {
194194
t.test('Should require JS by default', async (t) => {
195195
const ps = spawnTsNodeDev(
196196
[
197197
`--respawn`,
198198
//`--prefer-ts-exts`,
199199
`prefer/prefer.js`,
200200
].join(' ')
201-
).turnOnOutput()
201+
)//.turnOnOutput()
202202
await ps.waitForLine(/PREFER DEP JS/)
203203
await ps.waitForLine(/PREFER JS/)
204204
await ps.exit()
@@ -211,23 +211,31 @@ test.only('It should --prefer-ts', async (t) => {
211211
//`--prefer-ts`,
212212
`prefer/prefer`,
213213
].join(' ')
214-
).turnOnOutput()
214+
)//.turnOnOutput()
215215
await ps.waitForLine(/PREFER DEP JS/)
216216
await ps.waitForLine(/PREFER TS/)
217217
await ps.exit()
218218
t.pass()
219219
})
220+
220221
t.test('Use require all TS with --ts-prefer', async (t) => {
221222
const ps = spawnTsNodeDev(
222223
[
223224
`--respawn`,
224225
`--prefer-ts-exts`,
225-
`prefer/prefer.js`,
226+
//'--debug',
227+
`prefer/prefer`,
226228
].join(' ')
227-
).turnOnOutput()
229+
)//.turnOnOutput()
228230
await ps.waitForLine(/PREFER DEP TS/)
229231
await ps.waitForLine(/PREFER TS/)
232+
233+
setTimeout(() => replaceText('prefer/prefer-dep.ts', 'DEP', 'DEP MOD'), 250)
234+
235+
await ps.waitForLine(/PREFER DEP MOD TS/)
236+
230237
await ps.exit()
231238
t.pass()
239+
replaceText('prefer/prefer-dep.ts', 'DEP MOD', 'DEP')
232240
})
233241
})

0 commit comments

Comments
 (0)