guide, Tailwindcss, UI, css, elixir, phoenix

Add Tailwind CSS to Elixir Phoenix 1.4

While starting a greenfield Elixir Phoenix app, we looked at some ways we could manage the UI, and landed on Tailwind CSS.

TailwindCSS: A Utility-First CSS Framework for Rapid UI Development

We're going to be adding Tailwind CSS to a new Phoenix 1.4 app, so let's get to it.

This guide assumes you have Phoenix installed and are ready to start a new project.

Create Phoenix Application

Let's create a new app:

$ mix phx.new tailwind

And install the frontend dependencies.

Next, prepare the application:

$ cd tailwind
$ mix ecto.create
$ mix phx.server

And ensure that your app is running on localhost:4000

Add Tailwind CSS

cd into the assets directory:

$ cd assets

Let's add some dependencies and tailwindcss using yarn

$ yarn add --dev autoprefixer postcss postcss-loader tailwindcss

While still in the assets directory, run the tailwindcss initializer helper:

$ ./node_modules/.bin/tailwind init tailwind.config.js

This will create a default config file for tailwind at: assets/tailwind.config.js

Configure Postcss

Create a new assets/postcss.config.js file with this content:

const tailwindcss = require('tailwindcss');

module.exports = {
  plugins: [
    tailwindcss('./tailwind.config.js'),
    require('autoprefixer'),
  ],
};

And add the postcss-loader to the webpack config. Open assets/webpack.config.js and update the module rules to include postcss:

...

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          { loader: 'postcss-loader' }
        ]
      }
    ]
  },

...

Configure app.css

Tailwind's library is injected using some custom imports.  Open assets/css/app.scss and update it to this:

@import "tailwindcss/base";

@import "tailwindcss/components";

@import "tailwindcss/utilities";

NOTE: be sure to remove the @import "./phoenix.css"; line.

Test it out in the browser:

This should get everything initialized and configured to use Tailwind CSS in your application.  If you view the updates in the browser, it still looks strange but you can see the Tailwind's defaults are now being used:

Conclusion

This was just a quick guide on how to integrate Tailwind CSS into your greenfield Elixir Phoenix app, and should help with developing a powerful UI.

We're enjoying working with Tailwind CSS, and will likely post more detailed articles on how we tackle different elements.  But that should do it for this post.

Thanks for reading!  

Follow me on twitter if you enjoy our articles: @phxroad

Author image

About Troy Martin

Husband, Father & Software Developer who tinkers with writing and building things.
  • Hamilton, ON