Why do I see “define not defined” when running a Mocha test with RequireJS?

前端 未结 5 1743
暗喜
暗喜 2020-12-23 20:22

I am trying to understand how to develop stand-alone Javascript code. I want to write Javscript code with tests and modules, running from the command line. So I have insta

5条回答
  •  感动是毒
    2020-12-23 21:06

    I don't use requirejs so I'm not sure what that syntax looks like, but this is what I do to run code both within node and the browser:

    For imports, determine if we are running in node or the browser:

    var root =  typeof exports !== "undefined" && exports !== null ? exports : window;
    

    Then we can grab any dependencies correctly (they will either be available already if in the browser or we use require):

    var foo = root.foo;
    if (!foo && (typeof require !== 'undefined')) {
        foo = require('./foo');
    }
    
    var Bar = function() {
        // do something with foo
    }
    

    And then any functionality that needs to be used by other files, we export it to root:

    root.bar = Bar;
    

    As for examples, GitHub is a great source. Just go and check out the code for your favorite library to see how they did it :) I used mocha to test a javascript library that can be used in both the browser and node. The code is available at https://github.com/bunkat/later.

提交回复
热议问题