With the new project architecture proposed for Phoenix 1.3 there’s a lack of information on how to set a custom frontend.
So, in this post I’ll set a Vue.js app for the front, served by webpack.
Why webpack? To me Brunch is not enough, the tooling that supports Vue is currently better on
Webpack so we’ll use it.
Getting started
To get this settings you should have Phoenix version ~1.3 installed. If you don’t have it, at the
moment of this writing, you can just run:
Assuming you have Mix and Elixir installed, right?
Then let’s create a new Phoenix project by running (on your desired path):
And select no when asking to install dependencies, this will make easier to change settings. Notice that we’re not running mix phoenix.new anymore.
We could have added --no-brunch to our command but it’s easier this way since we can just delete
the brunch configuration and dependencies, plus it will create the assets folder (where our Vue
app will live) for us.
Then let’s move to our project directory and install Phoenix deps.
No we can start with our configuration, first we’ll visit the assets directory and remove the brunch-config.js file:
And while here, I’ll rename the js folder to src (just a personal preference) and remove the
css folder.
Lets update our package.json file to look like this (basically remove al brunch dependencies):
We’re now ready to fetch our personalized dependencies (you can use npm or yarn):
And the dev dependencies too:
We can also add suport for sass and stylus preprocessors:
Let’s add some scripts to our package.json file:
And then let’s create our main Webpack configuration file on the assets folder:
Open it and copy this:
Basically we’re declaring our app’s entry point ./src/main.js and exporting everything to the
priv/static folder of our project root path. We’re also extracting all styles from Vue components
files to a single css file. Basic support for images and font files is also added.
Go to the src directory and create the components folder and some files:
Edit the 3 files to look like these:
Finally let’s add our .babelrc file to the assets folder:
For now, we’re done with the Vue & Webpack part, now lets configure our Phoenix app.
Return to our main project folder phoenix_vue. First we’ll edit our .gitignore, find the ‘Static
artifacts’ section and add the following:
Next we’re going to edit the config/dev.exs file, let’s add this to the watchers section:
This way we can watch changes on the assets folder and recomplie with webpack using Phoenix’s
hot reaload functionality.
That’s it for config, now lets update our Phoenix views:
Let’s edit the templates/layout/app.html.eex file and clean the body.
And the templates/page/index.html.eex file to simply show:
And that’s it! If we go to the project root path and run iex -S mix phx.server we will see our
Vue.js content served by Phoenix.