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,283 thoughts on “Using RequireJS exports with CoffeeScript

  1. Почему пользователи выбирают площадку KRAKEN?

    Маркетплейс KRAKEN заслужил доверие многочисленной аудитории благодаря сочетанию ключевых факторов.
    Во-первых, это широкий и разнообразный ассортимент, представленный сотнями продавцов.
    Во-вторых, интуитивно понятный интерфейс
    KRAKEN, который упрощает навигацию, поиск товаров и управление заказами даже
    для новых пользователей.
    В-третьих, продуманная система безопасных транзакций, включающая механизмы разрешения
    споров (диспутов) и возможность использования условного депонирования, что минимизирует риски для обеих сторон
    сделки. На KRAKEN функциональность сочетается с внимательным отношением к безопасности клиентов, что делает процесс покупок более предсказуемым,
    защищенным и, как следствие, популярным среди
    пользователей, ценящих анонимность и надежность.

  2. Wow, marvelous weblog format! How long have you ever been running a blog for?
    you make blogging glance easy. The whole look of your site is excellent, as neatly as the content material!

  3. Эта разъяснительная статья содержит простые и доступные разъяснения по актуальным вопросам. Мы стремимся сделать информацию понятной для широкой аудитории чтобы каждый мог разобраться в предмете и извлечь из него максимум пользы. Провести детальное исследование – срочный вызов врача нарколога

  4. Wow that was unusual. I just wrote an really long comment but after I clicked submit my comment didn’t show up.
    Grrrr… well I’m not writing all that over again. Anyways, just
    wanted to say great blog!

  5. Have you ever considered about adding a little bit
    more than just your articles? I mean, what you say is important and
    all. Nevertheless imagine if you added some great visuals or video clips to give your posts
    more, “pop”! Your content is excellent but with images and videos, this
    blog could certainly be one of the most beneficial in its
    niche. Terrific blog!

  6. этот сайт дешевая накрутка премиум участников РІ тг таргетированные

  7. Everything is very open with a precise description of the
    issues. It was definitely informative. Your website is very useful.
    Thanks for sharing!

  8. Нужна бесплатная юридическая консультация? Переходите по запросу консультация юриста 24 часа в Ростове-на-Дону и получите помощь опытного юриста по любым правовым вопросам: семейные споры, долги, недвижимость, трудовые конфликты, защита прав потребителей и многое другое. Задайте вопрос онлайн или по телефону и получите подробный разбор вашей ситуации и рекомендации по дальнейшим действиям. Консультация проводится бесплатно и конфиденциально.

  9. در آخر کار

    برای اون گروهاز کاربرا که

    سرگرمی‌های پولی

    فعال هستن

    این صفحه

    مطمئناً می‌تونه

    مناسب باشه

    همچنین

    وبسایت‌هایی مثل

    enfejar onlіne

    و

    sib-bet

    شناخته شدن در این حوزه

    در نهایت

    ازش راضی بودم

    و

    باز هم

    برمیگردم بهش

    Ꮇy webb site … سایت اینترنت (topsazeco.ir)

  10. I do not even know how I ended up here, but I thought
    this post was great. I do not know who you are but definitely you are going
    to a famous blogger if you are not already ;) Cheers!

  11. Thank you, I’ve just been searching for information about this
    subject for a while and yours is the best I’ve discovered till
    now. However, what concerning the conclusion? Are you positive concerning the source?

  12. Hi there! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing several
    weeks of hard work due to no backup. Do you have any
    solutions to protect against hackers?

  13. Every weekend i used to go to see this website, for the reason that i wish for enjoyment, for the reason that this this web page
    conations in fact nice funny data too.

  14. whoah this blog is excellent i like reading your posts.
    Stay up the good work! You already know, many individuals are hunting around for this information, you could help them greatly.

  15. Thanks for a marvelous posting! I definitely enjoyed reading it, you’re a great author.I will
    be sure to bookmark your blog and will come back
    later on. I want to encourage you to ultimately continue your great posts, have a nice holiday weekend!

  16. Whats up very nice blog!! Guy .. Beautiful .. Superb .. I’ll bookmark your blog and
    take the feeds also? I’m glad to search out so many helpful
    information here within the post, we need develop more strategies on this regard,
    thanks for sharing. . . . . .

  17. El portal Deporte Ecuador es una plataforma informativa centrada en el análisis del ecosistema digital del deporte ecuatoriano.
    La plataforma integra artículos que analizan la evolución del
    deporte nacional en relación con la tecnología, la data y las tendencias
    de uso actuales.
    A diferencia de los sitios convencionales, Deporte Ecuador no se limita a cubrir resultados
    o noticias. La propuesta se basa en interpretar el funcionamiento
    del ecosistema deportivo moderno: el modo en que los usuarios usan las plataformas, qué elementos determinan su comportamiento y cómo evolucionan los estándares de calidad online.

    El contenido del sitio se estructura en torno a distintos ejes temáticos.
    En primer lugar, se evalúan las plataformas deportivas desde el punto de vista
    del usuario, la estabilidad y consistencia del servicio.
    Por otro, se estudian las dinámicas del mercado, etapas de digitalización y cambios en las formas de consumo deportivo en el país.

    Además, el portal también cubre cuestiones regulatorias, la protección digital y la toma de decisiones dentro del entorno
    online. Esto permite ofrecer una visión más completa del sector, mezclando evaluación técnica, contexto local y comportamiento 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.

    La plataforma se enfoca en usuarios que quieren comprender el deporte más allá de lo
    básico: considerando su dimensión tecnológica
    y cómo influye en la vida diaria.
    El texto menciona que hay un enlace disponible para ampliar el artículo.

  18. At this time it looks like BlogEngine is the preferred blogging platform available right now.
    (from what I’ve read) Is that what you’re using on your blog?

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>