Laravel-Mix is "an elegant wrapper around Webpack for the 80% use case". It has nothing to do with Elixir's Mix and does not require Laravel to work!
Create a new phoenix application with mix phx.new
. You may choose to add the --no-brunch
flag to stop brunch from being intiailized, but I personally prefer leaving that in and replacing brunch so that the folder structure is set up for me.
$ mix phx.new demo
cd
into your project.
$ cd demo/assets
Remove all of the devDependencies
in the package.json
file. Then install laravel-mix
and webpack
.
$ npm install laravel-mix webpack --save-dev
$ # or yarn add laravel-mix webpack --dev
Copy the default generated laravel-mix config into your project assets directory.
$ cp -r node_modules/laravel-mix/setup/webpack.mix.js ./
Open webpack.mix.js
and replace the default settings with the following. You can change or add anything you want; the API is included in the file. Also check out the docs, which are hosted in the GitHub repo.
mix.setPublicPath('../priv/static')
.js('js/app.js', 'js/app.js')
.sass('css/app.scss', 'css/app.css')
.copyDirectory('./static', '../priv/static');
mix.options({
clearConsole: false,
processCssUrls: false
});
Add a .babelrc
file in your assets folder to prevent babel from compiling phoenix's local npm files in ../deps
and fill it with the following:
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 2%"],
"uglify": true
}
}]
],
"ignore": [
"node_modules",
"deps"
]
}
If you are using the configuration above, you will need to replace assets/css/app.css
with assets/css/app.scss
, and you will need to import any (s)css files you want to include as they will not be automatically imported.
Then you will need to update the package.json
scripts so that it uses webpack instead of brunch.
{
"scripts": {
"deploy": "NODE_ENV=production webpack -p --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"watch": "NODE_ENV=development webpack --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
"dev": "NODE_ENV=development webpack --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
}
}
Update dev.exs
so that it uses these scripts. In the Endpoint
config, replace watchers
.
config :demo, Demo.Web.Endpoint,
watchers: [npm: ["run", "watch", # You might replace npm with yarn
cd: Path.expand("../assets", __DIR__)]]
You're almost done! Just remove the auto generated brunch-config.js
file, and the priv/static
folder (so that the old brunch-compiled files are removed) and then run the server.
$ mix phx.server
You're done! Hope you enjoy using the much simpler, yet more powerful: laravel-mix.
https://bowlsofsalt.com/setting-up-phoenix-and-vue/