7.4 Building your library

Now go back to the terminal and type this command:

npm i --save-dev webpack webpack-cli @babel/core @babel/preset-env babel-loader

Now go ahead and create a webpack.config.js at the root of project like so:

const path = require("path")

module.exports = {
  entry: path.resolve(__dirname, "src/index.js"),
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "index_bundle.js",
    library: "HNM",
    libraryTarget: "umd",
  },
  module: {
    rules: [
      {
        test: /\.(js)$/,
        exclude: /node_modules/,
        use: "babel-loader",
      },
    ],
  },
  mode: "development",
}

You can change the library field to however you would want to call the library!

Now also create a .babelrc at the root of the library directory like so :

{
  presets: ["@babel/preset-env"]
}

Now go to the package.json file and make these additions:

{
  "name": "HNM",
  "version": "1.0.0",
  "description": "",
  + "main": "dist/HNM.js",
  + "scripts": {
    + "build": "webpack"
  + },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Now go to the root of the project in your terminal and run this command:

npm run build

That’s it! Now you have the index_bundle.js file as your library and all you gotta do to use it is to include it as a script tag in your .html files!