Debugger listening on port 45864
/Users/WebSite/routes/xxx/page.ts:8
import request = require('request');
^^^^^^
SyntaxError: Unexpected reserved word
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
...
原因分析
在受到stackoverflow上某一个回答(http://stackoverflow.com/a/23113558/6001468) 的启发后,发现我的路由代码的code.ts和编译后的code.js文件都在express下的router文件夹下,而通过在这两个文件分别输出log发现均会输出,而实际上我希望只有.js文件被识别,ts文件在编译完成后就不再参与node的执行。
所以问题的原因就在于本不应该被node载入的.ts也被拉去进行执行。
通过断点后发现,问题的原因在于核心模块的module.js文件里面的343行:
// Given a file name, pass it to the proper extension handler.
Module.prototype.load = function(filename) {
debug('load %j for module %j', filename, this.id);
* @param file the file for which to determine module-ness.
* @returns {boolean}
*/
function isFileModule(file) {
var ext = path.extname(file);
// 新增:如果文件扩展名是.ts则不进行加载 --xxcanghai@博客园
if(ext === ".ts") {
return false;
}
// Omit dotfiles
// NOTE: Temporary fix in lieu of more complete (cross platform)
// fix using file flags/attributes.
if (path.basename(file, ext)[0] === '.') {
return false;
}
try {
// remove the file extension and use require.resolve to resolve known
// file types eg. CoffeeScript. Will throw if not found/loadable by node.
file = ext ? file.slice(0, -ext.length) : file;
require.resolve(file);
return true;
} catch (err) {
return false;
}