Never Punch Manticores
Learn how companies like Phone2Action are using npm in their front-end developmentJoin the conversation »

setup-webpack

2.5.0 • Public • Published

setup-webpack

Opinionated module of webpack loaders/plugins for simplified usage with examples for common use cases

Reduce boilerplate when creating your webpack config and keep your package.json slim.

Includes abstractions for transforming scss and pug, transpiling and polyfilling your javascript, minfication and reloading the browser on changes. All usage patterns are described with clear examples.

Table of Contents

Install

$ npm install setup-webpack
Install version v1

$ npm install setup-webpack@1

The documentation for v1 can be found here.

Upgrade to version v2

Version v2 upgrades webpack to v4, introducing a few breaking changes:

Require mode:

Either development or production.

{
  mode: "production",
}

Rename loaders field to rules:

v1:

{
  module: {
    loaders: [ babel, ... ]
  }
}

v2:

{
  module: {
    rules: [ babel, ... ]
  }
}

Deprecate uglify:

This deprecates the uglify plugin, as it is included in using optimization.minimize = true.

v1:

{
  plugins: [ uglify ]
}

v2:

{
  optimization: {
    minimize : true
  }
}

Change genPug to pug:

v1:

const pug = genPug( "index.html" );
 
{
  module: {
    loaders: [ pug.loader ]
  },
  plugins: [ pug.plugin ]
}

v2:

{
  module: {
    rules: [ pug( "index.html" ) ]
  }
}

Change genScss syntax:

v1:

const scss = genPug( "styles.css" );
 
{
  module: {
    loaders: [ scss.loader ]
  },
  plugins: [ scss.plugin ]
}

v2:

{
  module: {
    rules: [ scss.rule ]
  },
  plugins: [ scss.plugin ]
  optimization: {
    minimizer: [ scss.minimizer ],
  }
}

Usage

webpack.config.js:

const { babel, polyfill, browserSync, pug, genScss, img } = require( "setup-webpack" );
 
const sync = browserSync( 8000, 8080 );
 
const scss = genScss( "app.css" );
 
module.exports = {
  mode  : "production",
  entry : polyfill( "./app.bundle.js" ),
  output: {
    path    : path.resolve( __dirname, "build" ),
    filename: "app.js",
  },
  module: {
    rules: [ babel, pug( "app.html" ), scss.rule, scss.font, img( "img/" ) ],
  },
  plugins: [ scss.plugin, sync ],
  optimization: {
    minimize: true,
    minimizer: [ scss.minimizer ],
  },
};

Examples

All examples can be found in the examples/webpack folder.

Clone the repo to run the examples:

$ git clone https://github.com/jneidel/setup-webpack.git
Get up to speed with webpack

The default config location is in the root of the project, in a file named webpack.config.js.

The files to transpile are required or imported into a single bundle file:

app.bundle.js:

require( "./js/app" );
require( "./js/global-variables" );
require( "axios" );
 
require( "./scss/base-styles.scss" );
require( "./scss/app.scss" );
 
require( "./pug/app.pug" );

The bundle file will serve as an entry point for webpack, which will then split up the different file types again. Files of the same type (eg: .js) will be bundled into a single output file.

webpack.config.js:

const path = require( "path" );
const { pug, genScss } = require( "setup-webpack" );
 
const scss = genScss( "styles.css" ); // Set output path for css file
 
module.exports = {
  mode : "development", // Run webpack either on 'development' or 'production' mode
  entry: "./app.bundle.js", // Entry file that will be loaded into webpack,
  output: {                 // will be a bundle in our case
    path: path.resolve( __dirname, "build" ) // Specifies the output path for all files
    filename: "scripts.js", // Name of the main file to be exported, which
  },                        // will even be exported if no js files are being imported
  module: {
    rules: [
      scss.rule, // Extract scss and turn it into css
      pug( "index.html" ) // Extract pug, turn into html and save to path
    ]
  },
  plugins: [ scss.plugin ] // Save css to above specified path
  optimization: { // Production optimizations
    minimize: true, // Minimize js
    minimizer: [ scss.minimizer ], // Minimize css
  },
};

Required in every config:

  • mode
  • entry
  • output
    • output.path
    • output.filename

For a more in-depth intro, check out the webpack docs.

Transform scss into css

Transform scss or (sass) files to css.

View commented example at examples/webpack/scss.js.

To import local fonts and local images check out the corresponding API docs.

Transform pug into html

Transform pug to html.

View example at examples/webpack/pug.js.

To import local images check out the corresponding API docs.

Transform markdown into html

Transform markdown to html, applying GFM styles.

View example at examples/webpack/md.js.

Minify and transpile ES6 JavaScript

Reduce file size minify your code and, for compatibility with older browsers, polyfill and transpile ES6+ using babel.

View working commented example at examples/webpack/prod.js.

Because this process takes some time, you only want to run this in a production environment and not during development.

Reload browser on file changes

Any changes to the files included in the bundle will cause the project to be rebuild and the browser to reload.

View example at examples/webpack/sync.js.

The script has to run webpack in watch (-w) mode in order for browser-sync to be triggered once the project has been rebuilt.

$ webpack -w

Running this command in your terminal will require you to install the webpack-cli, to make use of the local installation use the command in a npm script.

"scripts": {
  "watch": "webpack -w"
}

Differentiate between development and production env

Minification and transpiling will only be triggered by environment variables that indicate a production environment.

View working example at examples/webpack/env.js.

Generating more than one output file

View example at examples/webpack/complete.js.

For each require in the entry file, this webpack config will output a transpiled file. If multiple files of the same type are required they will be bundled together in a single output file, making it easier for you to import them into your html document and edit their contents.

If no files of a specific type js|scss|pug are required in, webpack will simply not generate an output file of that type. Only the *.bundle.js file is necessary for the build to complete.

API

Cherry-pick the parts that you need using object destructuring:

const { babel, pug, genScss } = require( "setup-webpack" );

babel

Type: object Param: path Return: rule Examples: prod, env, complete

This loader transpiles ES6+ javascript for older browsers (more on babel) and minifies contents (shrinks down files, removing whitespace, redundant characters, more on minify).

Uses the env preset as well the minifier as options.

module.exports = {
  module: {
    rules: [ babel ]
  }
}

Uses babel-loader, babel-preset-env, babel-minify-webpack-plugin, babel-core under the hood.

polyfill( path )

Type: function Param: path Return: entry Examples: prod, complete

Polyfills functions and methods not yet available in all browsers. For more information see polyfill.

module.exports = {
  entry: polyfill( "./bundle.js" )
}

path:

Path to entry point bundle, which requires the code to be build.

Uses babel-polyfill under the hood.

genScss( path )

Type:
function, generator
Param:
path
Return:
{ rule, plugin, minimizer, font }
Examples:
scss, env, complete, font

Transpiles scss code in the entry file into css and writes the file to the given path.

Function generates a webpack rule, plugin and minimizer:

const scss = genScss( "app.css" );
 
module.exports = {
  output: {
    path: path.resolve( __dirname, "build" ),
  },
  module: {
    rules: [ scss.rule ],
  },
  plugins: [ scss.plugin ],
  optimization: {
    minimizer: [ scss.minimizer ],
  },
}
 
//=> Saved as build/app.css

font:

genScss also generates includes scss.font, which is a rule that should be included if you're importing local font files within your sass.

{
  module: {
    rules: [ scss.rule, scss.font ]
  }
}

Uses node-sass, mini-css-extract-plugin, sass-loader, css-loader, optimize-css-assets-webpack-plugin, file-loader under the hood.

pug( path, [data] )

Type: function Param: path, data Return: rule Examples: pug, pug-data, complete

Transpiles pug code in the entry file into html and writes the file to the given path.

module.exports = {
  output: {
    path: path.resolve( __dirname, "build" ),
  },
  module: {
    rules: [ pug( "./index.html" ), { headline: "Headline Content" } ],
  },
}
 
//=> Saved as build/index.html

path

Output path of the html file.

pug( "./index.html" )

[data]

Data to be passed to pug. In pug available as javascript variables.

pug( "./index.html", { place: "Berlin", time: Data.now() } )

Uses pug-html-loader, html-loader, extract-loader, file-loader under the hood.

img( directory )

Type: function Param: directory Return: rule Examples: img

This loader should only be used if you import local images in your pug or scss code.

Unlike the other loaders, this one only takes a directory, not a full path. The filename/extension will be copied over from the original, to not mix up different images.

module.exports = {
  output: {
    path: path.resolve( __dirname, "build" ),
  },
  module: {
    rules: [ img( "./img" ) ],
  },
}
 
//=> Saved as build/img/[name].[ext]

Uses file-loader under the hood.

md( path, [gfm, style, border] )

Type: function Param: path, gfm, style, border Return: rule Examples: md

Transpile required markdown files into html. GFM (github flavored markdown) styles are applied.

module.exports = {
  output: {
    path: path.resolve( __dirname, "build" ),
  },
  module: {
    rules: [ md( "./docs.html" ) ],
  },
}
 
//=> Saved as build/docs.html

path:

Output path for the html file.

md( "docs.html" )

gfm:

Default: sindresorhus/github-markdown-css

href that will be set as stylesheet source for applying the gfm styles.

md( "docs.html", "gfm.css" )

style:

href for an additional stylesheet. To customize the gfm styles.

md( "docs.html", "gfm.css", "custom.css" )

border:

Pass true to add a Github styled border around the <body>. See source module for rendered example: jneidel/gfm-loader.

md( "docs.html", "gfm.css", "custom.css", true )

Uses markdown-loader, html-loader, extract-loader, gfm-loader, file-loader under the hood.

browserSync( [proxy, port] )

Type: function Param: proxy, port Return: plugin Examples: sync, env, complete

Reloads brower windows connected on a given port, after webpack has rebuilt.

The proxy as well as the port are using localhost.

proxy:

Optional

Type: number

Default: 8000

Describes the port your server/app is running on.

port:

Optional

Type: number

Default: 8080

Describes the port which browser-sync will be running on. Only browser windows connected to this port will be reloaded.

Without a server:

Currently not supported in this module, but can be easily done using the browser-sync-cli:

In your npm package.json:

"scripts"{
  "build": "webpack -w",
  "sync": "browser-sync --server --files [ 'dist' ]", // Files/dirs to watch for changes
  "watch": "concurrently 'npm run build' 'npm run sync' --names '📦,🔄' --prefix name",
}

This script requires the global installation of concurrently.

Uses browser-sync, browser-sync-webpack-plugin under the hood.

Changelog

2.3.0:

  • Add md parameters (style, border)

Previous:

For upgrading to 2.x see install.

License

MIT © Jonathan Neidel

Install

npm i setup-webpack

DownloadsWeekly Downloads

3

Version

2.5.0

License

MIT

Unpacked Size

22.9 kB

Total Files

4

Last publish

Collaborators

  • avatar