Search code examples
reactjsbrowserifyelm

How to compile Elm with React in Browserify


I want to start using Elm in a React project, but they are not using Webpack, they are using Browserify with Gulp instead. How can I get Elm to be compiled with Browserify?


Solution

  • In the end, the best way around it I found was to compile the Elm code first, and only then compile the JS. This means that, unlike when using elm-webpack-loader where you can require the .elm files directly form JS, I have to require the compiled elm code.

    Here is a Gulp task to compile all Main.elm files in a directory or any of its subdirectories into a single .js file. You can then require the modules with

    import { Widget1, Widget2 } from "../compilation-folder/myapp.js" 
    

    Here is the task:

    const path = require("path");
    // const execSync = require("child_process").execSync;
    const shell = require("gulp-shell");
    const glob = require("glob");
    
    // Compiles all Main.elm files in a specified src folder and its subfolders
    // into the output file specified
    module.exports = (src, dest, outname) => {
        const output = path.join(dest, `${outname}`);
    
        return done => {
            glob(src + "/**/Main.elm", {}, (err, filesArray) => {
                const files = filesArray.join(" ");
                shell.task(`elm-make --yes ${files} --output=${output}`)(done)
            })
        }
    };
    

    You can use it like this:

    const buildElm = require("./fileWithCodeAbove.js")
    
    gulp.task("build-elm", buildElm("./elm-directory", "./build-directory", "myapp.js");