How to compile Elm in production with Phoenix and Webpack?

Hi,

I am using Elm as the front end for an Elixir/Phoenix app, which uses webpack to compile the Elm app during development.

Currently, when I deploy to production, the Elm app is still in an un-optimized state.

Does anyone have any pointers as to how I can compile Elm, optimized for production with webpack, when used as a front end for Phoenix?

Elm 0.19.1
Phoenix 1.5.0
Webpack 4.43.0

Thanks

In the webpack config you’ll have to add elm-webpack-loader so that it can compile the Elm code, if you don’t have it installed already you can add it with

$ cd my_project/assets
$ npm install --save-dev elm-webpack-loader

And then in the webpack config

      {
        test: /\.elm$/,
        exclude: [/elm-stuff/, /node_modules/],
        use: {
          loader: 'elm-webpack-loader',
          options: {
            debug: options.mode === "development",
            optimize: options.mode === "production"
          }
        }
      }

The optimize flag turns on additional optimizations in Elm, but doesn’t minify the code, to do that you’ll want to use something like uglify (https://guide.elm-lang.org/optimization/asset_size.html) or Terser (https://webpack.js.org/plugins/terser-webpack-plugin/).

For terser plugin you can configure it in the webpack.config.js file, something like this for minification and mangling.

  optimization: {
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          ecma: 5,
          compress: {
            pure_funcs: [
              "F2",
              "F3",
              "F4",
              "F5",
              "F6",
              "F7",
              "F8",
              "F9",
              "A2",
              "A3",
              "A4",
              "A5",
              "A6",
              "A7",
              "A8",
              "A9"
            ],
            pure_getters: true,
            keep_fargs: false,
            unsafe_comps: true,
            unsafe: true,
            passes: 2
          },
          mangle: true
        }
      })
    ]
  },

To gzip the assets for the frontend you will still need to run mix phx.digest, or put nginx in front of Phoenix to enable gzip.

4 Likes

Thanks, that’s just what I need.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.