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

前端 未结 2 936
庸人自扰
庸人自扰 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);
    
    0 讨论(0)
  • 2021-01-16 06:37

    Is there a way to use both of these .d.ts files in the same project

    I highly recommend going with commonjs everywhere. That is what the React community has spearheaded and it's a much simpler workflow. Just use CommonJS + webpack (to get lazy require.ensure from here).

    0 讨论(0)
提交回复
热议问题