1. 4
    Add a browser build to an npm module
    6m 16s

Add a browser build to an npm module

Share this video with your friends

Send Tweet

Currently, our library is being distributed as a CommonJS module, but we should support the browser as well. In this lesson, we're going to use webpack to create a UMD (Universal Module Definition) build of our module so users can consume it in a browser.

Mauricio Robayo
Mauricio Robayo
~ 7 years ago

For webpack v4:

import { join } from "path";

export default {
  entry: "./src/index.js",
  output: {
    path: join(__dirname, "dist"),
    libraryTarget: "umd",
    library: "starWarsNames"
},
  devtool: "source-map",
  module: {
    rules: [{ test: /\.js$/, use: "babel-loader" }]
  }
};

And the npm scripts for webpack:

    "build:umd": "webpack --output-filename index.umd.js --mode development",
    "build:umd.min": "webpack --output-filename index.umd.min.js --mode production",
Natalia
Natalia
~ 6 years ago

Thank you for the updated script!

Babs Craig
Babs Craig
~ 6 years ago

You might also need to npm i -D @babel/core and make sure to install npm i -D babel-core@7 if you get this error:

Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '@babel/core'

You want both the babel-loader and babel-core to be the same version - in this case version 7. Also, take out: { test: /\.json$/, use: "json-loader" } or it will cause an error as per:

https://stackoverflow.com/questions/49437048/module-parse-failed-unexpected-token-m-in-json-at-position-0