belgoros

belgoros

How to setup Zurb Foundation 6 with a Phoenix app

I can’t figure out how to set up Zurb Foundation 6 with a Phoenix app using webpack, no docs at all :frowning: . It was much easier to do that for Bootstrap 4 by just following this simple and useful tutorial.
Foundation docs say to add these 3 JS scripts at the end of a body:

<body>
    <h1>Hello, world!</h1>

    <script src="js/vendor/jquery.js"></script>
    <script src="js/vendor/what-input.js"></script>
    <script src="js/vendor/foundation.min.js"></script>
    <script>
      $(document).foundation();
    </script>

  </body>

But Phoenix builds everything in a single app.js if I’m not mistaken :thinking:
Here is what I added to app.js file:

import 'foundation-sites'
import css from "../css/app.scss"
import "phoenix_html"

I also renamed app.css → to app.scss and here is its content:

@import "./node_modules/foundation-sites/scss/foundation";

I also installed:

what-input.js
jquery.js
node-sass
sass-loader

Tneh I modified webpack.config.js as follows to use sass-loader and load app.scss:

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

When starting the server, it compiles without errors but:

  • there are no Foundation styles at all
  • there is Uncaught ReferenceError: $ is not defined error.

Any idea how to make it work? Thank you

Marked As Solved

belgoros

belgoros

Yo! I figured out how to make it work :slight_smile:.
Here is what I put in app.js file:

import $ from 'jquery'

require   ('what-input');
window.$ = $;


import Foundation from 'foundation-sites';
$(document).foundation();

import css from "../css/app.scss"
import "phoenix_html"

Then I modified app.scss as follows:

@import "~foundation-sites/scss/foundation";
@include foundation-everything();

I totally removed from app.html.eex template the JS line you suggested:

<script>
  document.onload = () => $(document).foundation()
</script>

and it has the only one generated by Phoenix:

<script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>

Finally, webpack.config.js contains this:

...
plugins: [
    require('autoprefixer'),
    new MiniCssExtractPlugin({ filename: '../css/app.css' }),
    new CopyWebpackPlugin([{ from: 'static/', to: '../' }]),
    new webpack.ProvidePlugin({ // inject modules as global vars
      $: 'jquery',
      jQuery: 'jquery', 'window.jQuery': 'jquery',
    })

Hope this helps.

Also Liked

pkbyron

pkbyron

@belgoros - your notes were essential for me working this out. Thanks so much for doing some hard yards in there!

Have it up and running!

phoenix “1.4.1”
foundation “6.6.1”
mac_osx: 10.15.3
node: 13.12.0

Getting Foundation working within Phoenix

Step 1. Getting Foundation in the right spot

I couldn’t get the foundation-cli working: it has a problem with node versions > 10.x; and as I am running node version 13.12.x, it was easier just to get the git version 6.6.1 from github.

  1. Download foundation 6.6.1 from github
  2. Unzip the download file into project_folder/assets/node_modules
  3. Make sure the directory name is foundation-sites (mine was called foundation-sites-develop)
  4. cd project_folder/assets/node_modules/foundation-site and view the README.md file. Within here there should be instructions on how to get foundation-site running…
    - npm install
    - npm start
    - after it starts, you can stop this running
  5. go back to your assets folder cd ../..

Step 2. Update your phoenix files

Change the extension of your app.css file

% mv assets/css/app.css -> assets/css/app.scss
// file: app.scss
@import "~foundation-sites/scss/foundation";
@include foundation-everything();
@import "./phoenix.css";

Edit your assets/js/app.js

// We need to import jquery for the webpack build of foundation
// And attach the foundation build to the document
import $ from 'jquery'
require('what-input');
window.$ = $;

import Foundation from 'foundation-sites';
$(document).foundation();

// We need to import the CSS so that webpack will load it.
// The MiniCssExtractPlugin is used to separate it out into
// its own CSS file.
import css from "../css/app.scss";

// webpack automatically bundles all modules in your
// entry points. Those entry points can be configured
// in "webpack.config.js".
//
// Import dependencies
//
import "phoenix_html"

// Import local files
//
// Local files can be imported directly using relative paths, for example:
// import socket from "./socket"

Step 3. Change the Phoenix setup

Here is my webpack.config.js file

!Important! - this includes a couple of packages you need to install first, cause if you don’t you will get errors on build.

% npm install jquery
% npm install sass-loader
% npm install node-sass
% npm install autoprefixer
% npm install webpack
const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

module.exports = (env, options) => ({
  optimization: {
    minimizer: [
      new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: false }),
      new OptimizeCSSAssetsPlugin({})
    ]
  },
  entry: {
    './js/app.js': ['./js/app.js'].concat(glob.sync('./vendor/**/*.js'))
  },
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, '../priv/static/js')
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.s?css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']
      }
    ]
  },
  plugins: [
    require('autoprefixer'),
    new MiniCssExtractPlugin({ filename: '../css/app.css' }),
    new CopyWebpackPlugin([{ from: 'static/', to: '../' }]),
    new webpack.ProvidePlugin({ // inject modules as global vars
      $: 'jquery',
      jQuery: 'jquery', 'window.jQuery': 'jquery',
    })
  ]
});

Hope this helps.

belgoros

belgoros

@pkbyron, thank you. You can find the project code source here, hope this helps :slight_smile:

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement