Thursday, July 20, 2017

Page-specific JavaScript together with third-party scripts and application-wide scripts in Webpack

Leave a Comment

TL;DR at the bottom.

I'm looking for a way to use Webpack like the way I'm using a Gulpfile right now.

My Gulpfile does the following:

  1. It Uglifies bower components (like jQuery, Air datepicker, MomentJS) into a single file (vendors.min.js)
  2. It concats every file in a specific folder, Uglifies the contents and processes it into another single file. (lib.min.js)
  3. It watches a folder for new/changed files, takes only the changed file, Uglifies it and saves it into a folder (these are my app files, they are page specific and can be loaded on demand).

So now I have 3 types of files:

  1. vendors.min.js

    • Loaded on every page in my application.
    • These make sure all the required third-party scripts are always available when you need them.
  2. lib.min.js

    • Loaded on every page as well.
    • This is my application's 'framework' 'Library', it mostly looks for data-attributes on elements and binds datepickers, tooltips but also provides some utility functions like cleaning Strings, formatting Strings as money etc.
  3. app/*.min.js

    • These give our developers a place to write page specific JavaScript.
    • They are loaded ONLY on that page.

I'm new to Webpack

I've watched a couple of video tutorials about it, I can see it is powerful and can help me to get further into JavaScript (read: use a more advanced structure and ES2015). I've also read through the Webpack tutorial but can't find how to make it work for my structure.

So the question is:

TL;DR

How can I use Webpack to have global (application wide) AND page-specific JavaScript in my applications and have them use third-party vendors (like jQuery, MomentJS, either through bower or npm or something).

1 Answers

Answers 1

You should have a entry config for each page like this:

entry: {     page1: ['./src/page1.js'],     page2: ['./src/page2.js'], } 

And output like:

output: {     path: `${__dirname}/app/`,     filename: '[name].min.js', }, 

And then use the CommonsChunkPlugin plugin to build a global file with things like jQuery, MomentJS

plugins: [     new webpack.optimize.CommonsChunkPlugin('vendors.and.lib.min.js'), ] 

(This is for webpack version 1)

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment