Create webpack library from scratch
I will start from minimal example so you can clearly understand the full concept and then will improve configuration for popular use-cases (ES6 transpiling, script-tag, and npm compatibility).
My node & npm versions:
$ node -v
v12.20.1
$ npm -v
7.5.4
Create folder:
mkdir p2 && cd p2
npm init
Pressed enter for all questions, any info could be changed later:
About to write to /home/ivan/devforth/p2/package.json:
{
"name": "p2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Install webpack
and webpack-cli
packages (CLI is used to run build command):
npm i -D webpack
npm install -D webpack-cli
webpack-cli is needed to run build command, previously it was built-in inside of webpack, but one day it started to say the cli moved into a separate package: webpack-cli. So to fix it just follow steps above and install both packages
Open package.json
file and check which versions were installed. For me it:
"devDependencies": {
"webpack": "^5.21.2",
"webpack-cli": "^4.5.0"
}
Create file main.js
with the next code:
export function p2 (x) {
return x + 2;
}
So this library will return a function named p2
which adds 2 to argument. For your needs it can do anything: create new object of a class or return some static object.
Create file webpack.config.js
in the same folder
webpack.config.js
With the next content:
'use strict';
const path = require('path');
module.exports = {
mode: 'production',
entry: './main.js',
output: {
path: path.resolve(__dirname, 'build'), // folder where library will be placed
filename: 'p2.commonjs2.js', // filename of the library
libraryTarget: 'commonjs2',
},
}
The libraryTarget
option is used to define a way how others will import the library. If you want the library to be used by npm install
and import library using import
operator, then use commonjs2
.
Add build
script to package.json
scripts:
"scripts": {
"build": "webpack --progress"
},
Also, change the main entry point in package.json
:
"main": "build/p2.commonjs2.js",
Run npm run build
Check output:
Now files will appear in build
folder:
$ ls build/
p2.commonjs2.js
To test library create file test.js
and place next:
const { p2 } = require('./build/p2.commonjs2.js');
console.log('p2:', p2)
console.log('p2(1):', p2(1))
You should see: