Slick Lazy Load Photo Grid Using Webpack 3

Webpack

Install Webpack. Version 3.10 is the latest as of this writing.

npm install --save-dev webpack

Create a webpack.config.js file in the root of the project. The CSS for this application is built using the process documented in my post last month, Webpack 3 Sass cssnano Autoprefixer Workflow. You are encouraged to read it for more information.

webpack.config.js
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
context: path.resolve(__dirname, './src'),
  entry: {
    app: './js/index.js',
    css: './sass/style.scss',
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: '[name].js'
  },
  module: {
    rules: [
    {
      test: /\.(css|scss)$/,
      use: ExtractTextPlugin.extract({
        fallback: 'style-loader',
        use: [
          {
            loader: 'css-loader',
            options: {
              minimize: true || {/* CSSNano Options */}
            }
          },
          {
            loader: 'postcss-loader'
          },
          {
            loader: 'sass-loader'
          }
        ]
      })
    },
    {
      test: /\.js$/,
      use: 'babel-loader'
    }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css'),
  ],
  devtool: '#eval-source-map'
}

Extract Text Plugin

Install the extract-text-webpack-plugin. This plugin is for extracting the css from the bundle into a style.css file.

npm install --save-dev extract-text-webpack-plugin

Autoprefixer

Autoprefixer evaluates the CSS and adds or removes vendor prefixes such as -webkit and -moz using caniuse.com data.

Install the autoprefixer PostCSS plugin.

npm install --save-dev autoprefixer
  • As devDependencies are installed using the --save-dev option, the package.json file will be updated so the node modules can be re-installed using npm install.

In the package.json file, add a browserlist configuration that lists minimum browser support for autoprefixer.

package.json
{
  "name": "photogrid",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "browserslist": [
    "> 2%",
    "last 2 versions",
    "ie > 9"
  ],

  ...
}

Create a PostCSS configuration module in the project root for requiring the autoprefixer plugin.

postcss.config.js
module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}

Babel

Babel is a JavaScript transpiler that converts the projects ES6 into ES5 JavaScript. Install Babel, loader and preset.

npm install --save-dev babel-core babel-loader babel-preset-env

Create a .babelrc configuration file in the root of the project.

.babelrc
{
  "presets": ["env"]
}

SASS and CSS Loaders

Install these loaders to handle the Sass and CSS for the extract-text-webpack-plugin.

SASS Loader compiles Sass to CSS, also requires node-sass.

npm install --save-dev sass-loader node-sass

PostCSS Loader processes CSS with PostCSS.

npm install --save-dev postcss-loader

CSS Loader resolves import at-rules and url functions in the CSS.

npm install --save-dev css-loader

Style Loader inlines <style></style> in the DOM.

npm install --save-dev style-loader

First Build

Install cross-dev to make the development and production NODE_ENV var easier to setup and use when running NPM scripts on various platforms, such as Windows and OS X.

npm install --save-dev cross-env

In the package.json file, define dev and build commands for npm-run-script. These are used to execute the development or production webpack bundle process.

package.json
...

  ],
  "scripts": {
    "dev": "cross-env NODE_ENV=development webpack --watch --progress --colors",
    "build": "cross-env NODE_ENV=production webpack --progress --hide-modules",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}

At the end of the webpack configuration JavaScript after the module.export, add this code for the respective dev and build npm scripts using the NODE_ENV settings.

webpack.config.js
...

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}
  • Note that the ellipsis … in the code snippet above is not a part of the actual code and is there only to denote code that is being skipped and not applicable to the example. Keep this in mind when you encounter an ellipsis in the remaining snippets. To view the entire file, examine the source code.

Using the npm-run-scripts alias npm run, execute the build.

npm run build

You should now have a new dist folder in the root of the project where the css and js are output. Load the webpage in a browser to see if the photo grid renders as expected.

The next page covers adding jQuery, the lightbox and slider.


Published by

Jim Frenette

Web Developer - views here are my own except those taken from people more clever than me.

Loading Disqus Comments ...
Loading Facebook Comments ...