Using Webpack 4 with Phoenix 1.3

Matt Ellis
Mar 25, 2018 · 3 min read

1. Make your way to project_web/assets

2. Remove Brunch (maybe)

yarn remove babel-brunch brunch clean-css-brunch uglify-js-brunchrm brunch-config.js

3. Add Webpack to your package.json

yarn add --dev webpack webpack-cli

4. Add Babel to your package.json

yarn add --dev babel-cli babel-core babel-loader babel-preset-es2015

5. Create a .babelrc file

{
"presets": [["es2015", { "modules": false }]]
}

6. Update your package.json scripts

"scripts": {
"deploy": "webpack --mode production",
"start": "yarn run watch",
"watch": "webpack --mode development --watch-stdin"
},

7. Create a webpack.config.js file

const path = require('path');module.exports = function(env) {
const production = process.env.NODE_ENV === 'production';
return {
devtool: production ? 'source-maps' : 'eval',
entry: './js/app.js', output: {
path: path.resolve(__dirname, '../priv/static/js'),
filename: 'app.js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
resolve: {
modules: ['node_modules', path.resolve(__dirname, 'js')],
extensions: ['.js'],
},
};
};

8. Update config/dev.exs

watchers: [yarn: ["run", "watch", cd: Path.expand("../assets", __DIR__)]]

9. Start Phoenix and watch Webpack happen

mix phx.server

10. Add hot reloading (optional)

yarn add --dev webpack-dev-server
"watch": "webpack-dev-server --mode development --hot --watch-stdin"
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
},
},
---
output: production
? {
path: path.resolve(__dirname, '../priv/static/js'),
filename: 'app.js',
publicPath: '/',
}
: {
path: path.resolve(__dirname, 'public'),
filename: 'app.js',
publicPath: 'http://localhost:8080/',
},
<script src="<%= static_path(@conn, "/js/app.js") %>"></script>
<%= if Mix.env == :dev do %>
<script src='http://localhost:8080/app.js'></script>
<% else %>
<script src="<%= static_path(@conn, "/js/app.js") %>"></script>
<% end %>

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade