Platform issue in require('os')

时光毁灭记忆、已成空白 提交于 2019-12-13 03:36:43

问题


I have created an Ionic 3(A5) app. I am running this as node-webkit (NW.JS) app on Mac. If I write inside index.html script tag and check, require('os') platform returns 'darwin' and require('fs') returns full set of object correctly. But if I write same script inside a .ts file - require('os') platform returns 'browser' and require('fs') returns empty object.

I am using @types/node in devDependencies.

Code inside index.html -

 var os = require('os');
 var fs = require('fs');
 console.log('Log from index.html');
 console.log('platform = ' + os.platform());
 console.log('fs = ');
 console.log(fs);

Code inside app.component.ts -

var os = require('os');
var fs = require('fs');
console.log('Log from app.component.ts');
console.log('platform = ' + os.platform());
console.log('fs = ');
console.log(fs);


回答1:


Based on a reply from The Jared Wilcurt @TheJaredWilcurt on gitter.im,

Node and Chromium don't know what a TS file is. you need to use something to transpile it to code that can actually be ran. TS is a meta-language, like Markdown, Sass, HAML, CoffeeScript, JSX, etc. Node only understands JavaScript, Chromium only understands HTML, CSS, and JS. If you are using something to transpile it and it alters your require statements, then that is the problem. You should inspect the actual code you are telling the environment to run.

This was happening because the Ionic transpiler was changing the code in some way. I changed the code

from

var os = require('os');
var fs = require('fs');

to

var os = nw.require('os');
var fs = nw.require('fs');

Now the only problem was that TypeScript compiler was not recognizing 'nw' as it was supposed to come at runtime. I have added

declare var nw: any;

on top. All fine now.



来源:https://stackoverflow.com/questions/49651592/platform-issue-in-requireos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!