Skip to content
This repository has been archived by the owner on Aug 23, 2018. It is now read-only.

Add CommonJS/Node/AMD snippet to end of compiled output #50

Closed
rtfeldman opened this issue Aug 27, 2015 · 4 comments
Closed

Add CommonJS/Node/AMD snippet to end of compiled output #50

rtfeldman opened this issue Aug 27, 2015 · 4 comments

Comments

@rtfeldman
Copy link

See elm/compiler#1029 for discussion that led to this.

The following should be incorporated into the output JS of compiled Elm files.

(function() {
  var Elm = ... // current emitted code goes here

  if (typeof define === "function" && define.amd) {
    define([], function() {
      return Elm;
    });
  } else if (typeof module === "object") {
    module.exports = Elm;
  } else {
    if (typeof this.Elm === "undefined") {
      this.Elm = Elm;
    } else {
      throw new Error("This page is trying to import multiple compiled Elm programs using the same `Elm` global object, which would cause conflicts. This can be resolved by using a module loader like RequireJS to import the compiled Elm programs into different objects.")
    }
  }
}).call(this);

PREVIOUS VERSION:

This version is more "stock" and will silently overwrite any previous Elm globals defined on the page...which seems far less desirable than crashing early with a helpful message.

(function() {
  var Elm = ... // current emitted code goes here

  if (typeof define === "function" && define.amd) {
    define([], function() {
      return Elm;
    });
  } else if (typeof module === "object") {
    module.exports = Elm;
  } else {
    this.Elm = Elm;
  }
}).call(this);
@rtfeldman
Copy link
Author

Just updated the original description to handle a case we ran into: if you add multiple compiled Elm programs to the same page, bad things will happen. The updated snippet will now:

  1. Prevent that from happening
  2. Explain to the user why that would be bad
  3. Recommend an alternative

@itrelease
Copy link

#63

@rtfeldman
Copy link
Author

Awesome! 🎉

@evancz
Copy link
Contributor

evancz commented Apr 5, 2016

Here is a version that uses an "early return" style that I think is easier to read.

    if (typeof define === "function" && define.amd)
    {
        define([], function() { return Elm; });
        return;
    }

    if (typeof module === "object")
    {
        module.exports = Elm;
        return;
    }

    if (typeof this.Elm === "undefined")
    {
        this.Elm = Elm;
        return;
    }

    throw new Error("blah blah blah");

}).call(this);

No need to do a PR or anything. I'll do it in the appropriate way.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants