Using webpack standalone

Posted by Markus Benning on November 07, 2018

Even static websites often depend on external libraries and frameworks like jQuery or Bootstrap. This article shows how to manage theses external dependencies with npm and include them in your project using webpack.

If your project does not yet have an package.json create one by executing

npm init

Add webpack and the css/style loaders as development dependency:

npm --save-dev webpack webpack-cli style-loader css-loader

Add the dependencies of your project (for example jquery, bootstrap):

npm --save jquery bootstrap

Create and app.js file and add imports for these modules:

import 'jquery';

import 'bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';

Then add the actual webpack configuration file webpack.config.js:

var webpack = require('webpack');
var node_dir = __dirname + '/node_modules';

module.exports = {
  entry: './app.js',
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
    })
  ],
  output: {
    path: __dirname + '/public',
    filename: 'bundle.js'
  },
  module: {
    rules: [{
      test: /\.css$/,
      loaders: [
        'style-loader',
        'css-loader'
      ]
    }]
  }
}

Add an build command to package.json:

{
  "scripts": {
    "build": "webpack --mode production"
  },
}

To build the bundle.js file execute this task using npm:

npm run build

The final step is to include this file in your HTML header:

    <script type="text/javascript" src="bundle.js"></script>