Automatically Building Your Phoenix Assets With Webpack

Posted by manukall on May 1, 2015

By default Phoenix (currently version 0.12) comes with support for I prefer using Webpack to build my assets, though. Fortunately creating a Phoenix app that uses Webpack instead of is pretty easy:

Create your new app with the --no-brunch flag:

mix /tmp/my_app --no-brunch

Initialize npm and install Webpack:

cd /tmp/my_app
npm init
npm install --save-dev webpack

Add webpack to the watchers array in your development config (/tmp/my_app/config/dev.exs):

config :my_app, MyApp.Endpoint,
  watchers: [{Path.expand("node_modules/webpack/bin/webpack.js"), ["--watch", "--colors", "--progress"]}]

Add a webpack config (/tmp/my_app/webpack.config.js)

module.exports = {
    entry: "./web/static/js/app.js",
    output: {
        path: "./priv/static/js",
        filename: "bundle.js"

Include the generated js file in your application template (/tmp/my_app/web/templates/layout/application.html.eex).


<script src="<%= static_path(@conn, "/js/app.js") %>"></script>


<script src="<%= static_path(@conn, "/js/bundle.js") %>"></script>

Create the source javascript file (/tmp/my_app/web/static/js/app.js):

console.log("Hello from Webpack");

Start the server (mix phoenix.server), open your browser and check the console.