Code Monkey home page Code Monkey logo

elm-esm's Introduction

Turn Elm compiler output into modern ES Modules

Wanna load Elm as ES Modules in your browser? Say no more. With this package you can easily do just that.

npx elm-esm make src/Main.elm --output=myElmModule.js

Then use your favorite way of loading it as a new ES module

<script type="module">
import { Elm } from './myElmModule.js';

Elm.Main.init({ node: document.body })
</script>

It's even possible to use your favorite ES6 features like dynamic-import or modulepreload now.

// this is great for lazy loading an Elm app
import('./myElmModule.js').then(({ Elm }) => {
  Elm.Main.init({ node: document.body })
});
<!-- preload our Elm module for faster startup when you need it -->
<link rel="modulepreload" href="./myElmModule.js">

It's like it's 2020 already ๐Ÿฅณ๐ŸŽ‰

CLI Usage

elm-esm accepts all the options that elm accepts. Run elm-esm --help for an overview.

npx elm-esm make src/Main.elm --output=myElmModule.js

# Or globally installed
npm i -g elm-esm
elm-esm make src/Main.elm --output=myElmModule.js

elm-esm accepts one extra option called --compiler=path/to/elm. By default it looks for an Elm compiler in the following order.

  1. In whatever you pass with the --compiler=path/to/elm flag, if present
  2. In the nearest node_modules/.bin
  3. In your $PATH

NodeJS Usage

Plugin authors or other tooling may want to use the transform as a standalone function. Here's how:

# install the package to your dependencies
npm i -D elm-esm

The module exports a named function called toESModule. It takes one argument, which is the compiled Elm code as a string. It returns the ESModule transformed code as a string.

const { toESModule } = require('elm-esm');

const transformedElmOutputAsESModule = toESModule(compiledElmOutput);

FAQs

How does that work under the hood?

It's just a few simple Regex transforms on the compiler output, designed to work under different circumstances. It only operates on necessary lines of code that are related to exporting. Some code that isn't needed is commented out, and one line to export in ES6 style is added.

Will this work in my browser?

Probably, yes. All modern Browsers support ES6 modules now. Check out the compatibility table.

How can I use this with Webpack/Parcel/Rome

I haven't 100% figured that out, but it should be pretty easy. elm-esm is designed to be a wrapper around elm. Most bundler plugins for Elm allow passing an option with a path to the Elm executable. Just pass the path to elm-esm instead. On the other hand why bundle when you can load the module in the browser directly? If you're looking to bundle your app, then you probably don't need this elm-esm.

Please open an issue if you run into problems here!

What about elm-test?

Don't use this for elm-test. elm-esm is meant for use in the browser. NodeJS still only has experimental support for ESM sigh.

But if you're looking to launch a Platform.worker Elm program in Deno, then elm-esm can generate the necessary ES module for you.

Does this work for all Elm versions?

It's only tested for Elm 0.19.1, but it may work with 0.19.0 too. Please open an issue if you run into problems here!

What if I compile to an HTML file?

Nothing happens. Having an inline script with type=module doesn't make sense with exports since I don't think you can import it anywhere else.

elm-esm's People

Contributors

christophp avatar wolfadex avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

elm-esm's Issues

Program with non-trivial Flags type does not compile

Hello,

the following bug was created on my https://github.com/marc136/snowpack-plugin-elm/issues/3 by @andreasewering
And as I copied the code to turn the compiled elm code into an es module from your repository, I think the change should also be propagated into your tool.

I fixed it in my repo with this change.

Regards,
marc


Full description

When comipling the following file with npx elm-esm make src/DocumentWithFlags.elm --output=elm-esm-output.js, you can open the compiled js output and will notice that at the end the call to _Platform_export is not fully replaced.

module DocumentWithFlags exposing (main)

import Browser
import Html exposing (..)
import Json.Decode


type alias Flags =
    -- Json.Decode.Value -- this would work
    { test : String }


main : Program Flags Model Msg
main =
    Browser.document
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }


type alias Model =
    { property : String
    }


init : Flags -> ( Model, Cmd Msg )
init _ =
    ( Model "", Cmd.none )


type Msg
    = Msg1
    | Msg2


update : Msg -> Model -> ( Model, Cmd Msg )
update _ model =
    ( model, Cmd.none )


subscriptions : Model -> Sub Msg
subscriptions _ =
    Sub.none


view : Model -> Browser.Document Msg
view _ =
    { title = "Document Title"
    , body =
        [ h1 [] [ text "loaded" ] ]
    }

The output ends with the following lines:

var $author$project$DocumentWithFlags$main = $elm$browser$Browser$document(
	{init: $author$project$DocumentWithFlags$init, subscriptions: $author$project$DocumentWithFlags$subscriptions, update: $author$project$DocumentWithFlags$update, view: $author$project$DocumentWithFlags$view});
/*
_Platform_export({'DocumentWithFlags':{'init':$author$project$DocumentWithFlags$main(
	A2(
		$elm$json$Json$Decode$andThen,
		function (test) {
			return $elm$json$Json$Decode$succeed(
				{test: test});
*/
		},
		A2($elm$json$Json$Decode$field, 'test', $elm$json$Json$Decode$string)))(0)}});}(this));
export const Elm = {'DocumentWithFlags':{'init':$author$project$DocumentWithFlags$main(
	A2(
		$elm$json$Json$Decode$andThen,
		function (test) {
			return $elm$json$Json$Decode$succeed(
				{test: test};

But it should be:

var $author$project$DocumentWithFlags$main = $elm$browser$Browser$document(
	{au: $author$project$DocumentWithFlags$init, aB: $author$project$DocumentWithFlags$subscriptions, aD: $author$project$DocumentWithFlags$update, aE: $author$project$DocumentWithFlags$view});
/*
_Platform_export({'DocumentWithFlags':{'init':$author$project$DocumentWithFlags$main(
	A2(
		$elm$json$Json$Decode$andThen,
		function (test) {
			return $elm$json$Json$Decode$succeed(
				{ag: test});
		},
		A2($elm$json$Json$Decode$field, 'test', $elm$json$Json$Decode$string)))(0)}});}(this));
*/
export const Elm = {'DocumentWithFlags':{'init':$author$project$DocumentWithFlags$main(
	A2(
		$elm$json$Json$Decode$andThen,
		function (test) {
			return $elm$json$Json$Decode$succeed(
				{ag: test});
		},
		A2($elm$json$Json$Decode$field, 'test', $elm$json$Json$Decode$string)))(0)}});};

elm-esm crashes

Something crashed unexpectedly. Please open an issue with this error message. https://github.com/ChristophP/elm-esm/issues/new

TypeError: Cannot read properties of null (reading 'toString')
    at findElmBinary (C:\Users\<user>\AppData\Roaming\npm\node_modules\elm-esm\src\run.js:15:12)
    at delegateToElmCompiler (C:\Users\<user>\AppData\Roaming\npm\node_modules\elm-esm\src\run.js:50:27)
    at run (C:\Users\<user>\AppData\Roaming\npm\node_modules\elm-esm\src\run.js:65:9)
    at Object.<anonymous> (C:\Users\<users>\AppData\Roaming\npm\node_modules\elm-esm\src\run.js:71:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Modularize makeESModule

Thanks for sharing such a useful implementation โœจ

One thing I'd like to request is that the distributed elm-esm npm provides importable makeESModule.

I'm imagining an interface like:

import { toESM } from 'elm-esm'

toESM(compiledElmProject)

I could build my own function by copying your code actually. However, I'm wondering if elm-esm becomes a single source of truth for this purpose in the community, and we can contribute when Elm core changes outcome in the future.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.