Unable to use requireJS and Node's Require in the same TypeScript project

前端 未结 2 935
庸人自扰
庸人自扰 2021-01-16 06:03

I have a typescript project targeted at both Node and the browser. I\'m using Node\'s require() in some scripts and requireJS\'s require() in othe

2条回答
  •  孤城傲影
    2021-01-16 06:31

    In the end what I needed was the ability to require() JS content that is compiled on the fly by the server -- which doesn't seem to work with web-pack.

    To suppress the errors from the typescript compiler in the original question, I commented out this line from require.d.ts (the RequireJS declaration file):

    declare var require: Require;
    

    and I used the {foo:bar}['f'+'oo'] trick to get tsc to 'forget' the type of the ambient require variable when assigning it to the typed requirejs variable, like so:

    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);
    

提交回复
热议问题