Universal JavaScript with Webpack

In notebook:
FrontEndMasters Creating an Open Source JavaScript Library on Github
Created at:
2017-07-18
Updated:
2017-07-18
Tags:
Webpack libraries JavaScript

##Create a browser build

Exports is not defined error in the browser (ES6 modules not yet supported in every browser)

commonjs is not supported either (and will not be).

Webpack will solve this. This step (Webpack) will solve the browser issue for those people who don't use a bundler already. Otherwise their bundler will solve this..

As a library author, it's not nice to require your users to use a bundler so we have to provide a solution.

He will go through Webpack very quickly, there are other resources to learn the details...

creates the config file webpack.config.babel.js

  // webpack.config.babel.js

// we can use ES6 (because the name is *.babel.js)
import {join} from 'path'

const context = join(__dirname, 'src')

export default {
  context,
  entry: './index',
  output: {
    path: join(__dirname, 'dist'),
    // target is UMD
    libraryTarget: 'umd',
    // name of the library
    library: 'starWarsNames',
  },
  devtool: 'source-map',
  dev : {
  }
  module: {
    loaders: [
      {test: /\.js$/, loaders: ['babel'], include: context},
      {test: /\.json$/, loaders: ['json'], include: context},
    ],
  },
}

For your library, you can just copy-paste this code.

He targets for UMD module format. He explains the reason for UMD format. We need a universal format for both browser (amd) and NodeJS (commonjs).

It puts your whole code in an IFEE with some checks inside it to know which module format is supported by the host environment. It creates a factory variable that holds either the modules or your exported modules as functions.

If it detects that neither amd nor module.exports is supported, then it sticks everything on a global root.genie variable.

The above stuff is mostly copy paste for most libraries.

Question: Can't we just do everything with npm scripts without Webpack?

We do them together. NPM scripts are easy for contributors.