Using RequireJS exports with CoffeeScript

If you are using the “exports” object in your RequireJS module definition and happen to also be using CoffeeScript then be careful to either return the exports object at the end of the function or explicitly return nothing from the function by typing “return” on the last line. Like so:

define((require, exports, module) ->
    exports.foo = 'bar'
    return
)

If you don’t return nothing or the exports object CoffeeScript will compile this:

define((require, exports, module) ->
    exports.foo = 'bar'
)

…to the following javascript:

define(function(require, exports, module) {
    return exports.foo = 'bar';
});

Where the return value will be the string ‘bar’. This is no good because if you return a value from your module definition function, RequireJs uses it instead of the exports object. So when you come to require your module, you’ll be passed a String, rather than an object with a “foo” property as you’d expect.

18,098 thoughts on “Using RequireJS exports with CoffeeScript

  1. Oh my goodness! Impressive article dude! Thank you, However I
    am going through issues with your RSS. I don’t understand why I am unable to
    subscribe to it. Is there anybody having identical
    RSS problems? Anyone who knows the answer will you kindly
    respond? Thanx!!

  2. El portal Deporte Ecuador es una plataforma informativa centrada en el análisis del ecosistema digital del deporte ecuatoriano.
    La web agrupa materiales que exploran cómo evoluciona
    el deporte en el país en el contexto de la tecnología, los datos y
    los nuevos hábitos de consumo.
    A diferencia de los sitios convencionales, Deporte Ecuador no se limita
    a cubrir resultados o noticias. La prioridad es comprender el funcionamiento del ecosistema
    deportivo moderno: el modo en que los usuarios usan las plataformas, qué variables afectan sus decisiones y cómo
    se redefinen las métricas de calidad digital.
    La información dentro del portal se organiza alrededor de varios
    ejes clave. En primer lugar, se evalúan las plataformas deportivas
    considerando la experiencia del usuario, su solidez
    y continuidad. Por otra parte, se examinan las dinámicas del
    mercado, procesos de transformación digital y la evolución de los hábitos de
    consumo deportivo en el país.
    Además, el proyecto analiza temas vinculados a la regulación, la protección digital
    y los procesos de decisión en entornos digitales.
    Esto ayuda a construir una imagen más amplia del sector,
    fusionando análisis técnico, contexto local y conducta del usuario.

    El propósito central es brindar datos claros, bien estructurados y
    funcionales para entender el papel del deporte en la era digital.
    No se trata de ofrecer respuestas simplificadas, sino de ayudar a interpretar un entorno cada vez más complejo.

    Deporte Ecuador está dirigido a usuarios que buscan entender el deporte más allá de la superficie: incluyendo su componente
    tecnológico y su impacto en la experiencia cotidiana.

    El texto aclara que hay un enlace para ver la versión completa del artículo.

  3. NewULife Ranks. Invite to my NewUlife Testimonial.

    Feel free to surf to my web page … mats inc commercial flooring (Leif)

  4. Эта статья сочетает в себе как полезные так и интересные сведения которые обогатят ваше понимание насущных тем. Мы предлагаем практические советы и рекомендации которые легко внедрить в повседневную жизнь. Узнайте как улучшить свои навыки и обогатить свой опыт с помощью простых но эффективных решений. Это ещё не всё… – вызов наркологической помощи

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>