无法在同一个TypeScript项目中使用requireJS和Node的Require
我有一个针对Node和浏览器的打字稿项目。 我在某些脚本中使用了Node的require()
,并且在其他脚本中require()
。 我的项目目录如下所示:
myProject \-- a.ts \-- b.ts \-- node.d.ts \-- require.d.ts
其中a.ts
包含:
/// <reference path="./node.d.ts" /> var cp = require('child-process'); var a = 'hello world' export = a
和b.ts
包含:
/// <reference path="./require.d.ts" /> require('hello',function(x){console.log('world')}); var b = 'hello world' export = b
其中require.d.ts
和node.d.ts
从DefinitlyTyped获得。
当我编译我的项目,我得到这些错误:
b.ts(2,1): error TS2346: Supplied parameters do not match any signature of call target. require.d.ts(396,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'Require'.
我使用这个成语来确定加载哪个模块,所以我没有在浏览器中加载节点模块,反之亦然。
if(typeof module !== 'undefined' && module.exports){ // We're in a Node process }else{ // We're in an AMD module in the browser: }
有没有办法在同一个项目中使用这两个.d.ts
文件。 看来在单独的模块中使用它们是不够的。
有没有办法在同一个项目中使用这两个.d.ts文件
我强烈build议commonjs
使用commonjs
。 这就是React社区所带头的,这是一个更简单的工作stream程。 只需使用CommonJS + webpack(从这里获得懒惰require.ensure
)。 🌹
在浏览器环境中还有一个TypeScript快速入门。
最后,我需要的是能够require()
JS内容,由服务器dynamic编译 – 这似乎不适用于Web包 。
为了在原始问题中抑制打字稿编译器的错误,我从require.d.ts
(RequireJS声明文件)中注释掉了这一行:
declare var require: Require;
我使用{foo:bar}['f'+'oo']
技巧让tsc
在将其分配给types化的requirejs
variables时将' require
variables的types'忘记',如下所示:
var requirejs:Require; // requirejs if(typeof module !== 'undefined' && module.exports){ // We're in a Node process requirejs = require('requirejs'); }else{ // We're in an AMD module in the browser: requirejs = {require:require}['req'+'ire']; } // use requirejs for dynamic require statements requirejs(gather_requirements(),do_things);
- 如何在没有Typescript / TSD定义的情况下将库导入节点?
- Froala编辑器不支持Angular 4与打字稿
- VS.代码中的Node.js TypeScriptdebugging
- 在Node.js的TypeScript 1.6.2中导入jQuery
- 为了实现Angular SSR,node.js服务器需要webpack + typescript
- 在单个包文件中join文件,但是避免在包中发布Commonjs文件
- VS Code Intellisense适用于Javascript文件,但不适用于TypeScript文件
- 打字稿错误:TS2304:找不到名称'$'
- 我如何得到这个Typescript Webpack项目编译没有错误?