Adding Semantic UI Sass to Phoenix with Webpack

Once you have Webpack and Sass set up for your Phoenix 1.3 project, replacing Bootstrap with Semantic UI is a breeze.

If you prefer Brunch to Webpack, see this article.

Step 1: Add jQuery

$ cd assets
$ yarn add jquery

Next, automatically load jQuery inside webpack.config.js:

const providePlugin = new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
});

Find the plugins entry in your Webpack config and add providePlugin there.

If you want jQuery to be available in your browser’s dev console, also edit app.js:

window.$ = window.jQuery = jQuery;

Example commit

Step 2: Add Semantic UI

Assuming you’re in project root:

$ cd assets
$ yarn add -D semantic-ui-sass

Copy images and fonts from Semantic UI Sass GitHub repo to a new folder assets/static/semantic-ui.

Example commit

Step 3: Configuration

Have Phoenix pick up the static assets you copied earlier by editing endpoint.ex:

plug Plug.Static,
at: "/", from: :my_app, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt semantic-ui)

Example commit

Step 4: Usage

Now we’re ready to use Semantic UI. Add to app.js:

import "semantic-ui-sass/js/api";
import "semantic-ui-sass/js/colorize";
import "semantic-ui-sass/js/form";
import "semantic-ui-sass/js/state";
import "semantic-ui-sass/js/visibility";
import "semantic-ui-sass/js/visit";
import "semantic-ui-sass/js/site";
import "semantic-ui-sass/js/accordion";
import "semantic-ui-sass/js/checkbox";
import "semantic-ui-sass/js/dimmer";
import "semantic-ui-sass/js/dropdown";
import "semantic-ui-sass/js/embed";
import "semantic-ui-sass/js/modal";
import "semantic-ui-sass/js/nag";
import "semantic-ui-sass/js/popup";
import "semantic-ui-sass/js/progress";
import "semantic-ui-sass/js/rating";
import "semantic-ui-sass/js/search";
import "semantic-ui-sass/js/shape";
import "semantic-ui-sass/js/sidebar";
import "semantic-ui-sass/js/sticky";
import "semantic-ui-sass/js/tab";
import "semantic-ui-sass/js/transition";

Replace with import “semantic-ui-sass”; if you just want all the modules.

Add to app.scss:

$import-google-fonts: true;
$icons-font-path: '/semantic-ui';
$flags-image-path: '/semantic-ui';
// Fix: https://github.com/aniftyco/semantic-ui-sass/issues/3
i.flag:not(.icon)::before {
background: url("#{$flags-image-path}/flags.png") no-repeat -108px -1976px;
}
@import '~semantic-ui-sass/scss/globals/all';
@import '~semantic-ui-sass/scss/elements/all';
@import '~semantic-ui-sass/scss/collections/all';
@import '~semantic-ui-sass/scss/views/all';
@import '~semantic-ui-sass/scss/modules/all';

Now you can hand-pick the modules you want. Simply replace all with the exact module names that you want to include.


If you take a look at the GitHub repo, there’s a Semantic UI test page along with a ‘Deploy to Heroku’ button that you can use for verifying that both minified CSS and JavaScript are working correctly in production.