Use webpack to build your own npm package

Posted by moboter on Thu, 06 Jan 2022 10:10:09 +0100

Introduction: I have recently done several projects. I want to extract the public parts and set them as npm packages separately so that other projects can be used and save the trouble of repeated writing. After looking for a long time on the Internet, I finally found a way to package my own package to npm and support the use of browser and node environment at the same time. It is very convenient. Let's make a development summary now.

catalogue

  • preparation
  • Write a method
  • pack
  • test
  • release

preparation

  • Query whether the npm package name exists

Because it is a published public package, the package name must be unique and cannot be repeated. If you are not sure whether your package name is already used, you can open the command line window to query. If it is not found, you can continue. Otherwise, change a package name.

npm search fegq-test

If the results show that the package name is not used, you can rest assured to publish your package.

No matches found for "fegq-test"

For example, I released a test package fsdgq test before, and the search results will come out. At this time, I need to change the package name to avoid errors.

# Query package name
npm search fsdgq-test

# Query results
NAME                      | DESCRIPTION          | AUTHOR          | DATE       | VERSION  | KEYWORDS
fsdgq-test                |                      | =ioguanqi       | 2021-12-02 | 1.0.1    |
  • Create a new folder and initialize a package.

The name of this folder will be the package name by default. Of course, it can also be followed by package JSON configuration file.

mkdir fegq-test
cd fegq-test
npm init

The initialization process is as follows:

his utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (fegq-test) # Enter the package name. The default folder here is the package name, which is omitted
version: (1.0.0) 0.0.1 # Version number, I write 0.0.1 here because it is the first version just released
description: this is a test package. # I'll write a brief description of the package here
entry point: (index.js) ./dist/mytest.js # The entry file is the place to import after others download your package. Here I will write the address of the packaged file
test command: jest # After the test command package is written, you can choose a test language to test. Here I use jest to test
git repository: https://github.com/gitguanqi/fegq-test.git # warehouse address. You can write github,gitee and other warehouse addresses. Here I will create a new GitHub test warehouse
keywords: fegq-test,test # Keywords, set multiple commas to separate them, and fill in the relevant information belonging to this package
author: gitguanqi # Author Bao, just write it yourself
license: (ISC) MIT # The package complies with the software development protocol, commonly used are MIT,GPL3, etc
About to write to F:\web\front\test\template\npmlx\fegq-test\package.json:

{
  "name": "fegq-test",
  "version": "0.0.1",
  "description": "this is a test package.",
  "main": "./dist/mytest.js",
  "scripts": {
    "test": "jest"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/gitguanqi/fegq-test.git"
  },
  "keywords": [
    "fegq-test",
    "test"
  ],
  "author": "gitguanqi",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/gitguanqi/fegq-test/issues"
  },
  "homepage": "https://github.com/gitguanqi/fegq-test#readme"
}


Is this OK? (yes) # Enter directly

Check the configuration information package json.

{
  "name": "fegq-test",
  "version": "0.0.1",
  "description": "this is a test package.",
  "main": "./dist/mytest.js",
  "scripts": {
    "test": "jest"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/gitguanqi/fegq-test.git"
  },
  "keywords": [
    "fegq-test",
    "test"
  ],
  "author": "gitguanqi",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/gitguanqi/fegq-test/issues"
  },
  "homepage": "https://github.com/gitguanqi/fegq-test#readme"
}
  • Install required dependent packages

Then install Babel, webpack and jest series dependency packages

npm i babel-core babel-loader babel-plugin-add-module-exports babel-preset-env eslint webpack webpack-cli clean-webpack-plugin babel-jest jest jquery
  • Create a new webpack config. JS configuration file, write the following content.
// webpack.config.js
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    mode: 'production', // environment
    entry: './index.js', // Entry file
    output: {
        path: path.resolve(__dirname, './dist'), // Output folder
        filename: 'mytest.js', // File name
        libraryTarget: 'umd', // Packaging method
        globalObject: 'this', // Global object
        library: 'mytest', // Class library name
    },
    plugins: [
        new CleanWebpackPlugin(), // Clear last package
    ],
    externals: {
        jquery: "jQuery", // Do not participate in package compilation
    },
}

output. Total supported values for librarytarget:

  • var - default
  • assign
  • this
  • window
  • global
  • commonjs
  • commonjs2
  • amd
  • umd
  • jsonp

If you use packages such as jQuery and Vue and don't want to package them in your own package, you can use externals.

For example:

externals: {
    jquery: "jQuery" 
},

Write a method

The preparatory work has been completed. Now let's get to the point, such as writing a package of two methods of addition and dom operation.

  • Create a new lib folder and place the main methods in the face.
mkdir lib
  • Writing method
// ./lib/index.js
const $ = require('jquery');

function addCon () {  
    $('#content').html('<h1>hello</h1>');
}

function add (a,b) {  
    return a+b;
}

const test = {
    addCon,
    add,
}

module.exports = test;
  • Introducing lib content

Create a new index. In the package root directory JS as the webpack entry file and import the method just written.

// ./index.js
const mytest = require('./lib/index');
module.exports = mytest;

In this way, you can write your own package, and then proceed to the packaging operation.

pack

  • Add packaging command.

In package A script command webpack is added to the scripts of JSON.

As follows:

{
  // ...
  "scripts": {
    "build": "webpack"
  },
  // ...
}
  • Start packing

Run npm run build to start packaging.

# Start package command
npm run build

# Packaging results
> fegq-test@0.0.1 build
> webpack

asset mytest.js 617 bytes [emitted] [minimized] (name: main)
./index.js 64 bytes [built] [code generated]
./lib/index.js 218 bytes [built] [code generated]
external "jQuery" 42 bytes [built] [code generated]
webpack 5.64.4 compiled successfully in 425 ms

After successful packaging, you can now conduct simple tests.

test

jest is used here for testing.

File naming rules: < test name > test. js.

  • Create a new test file add test. js.

Write the following to test the add method.

// ./my.test.js
const add = require('./dist/mytest').add;

test('adds 1 + 2 to equal 3', () => {
    expect(add(1,2)).toBe(3);
})
  • Start test
# Start test command
npm run test

# test result
> fegq-test@0.0.1 test
> jest

 PASS  ./add.test.js
  √ adds 1 + 2 to equal 3 (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.851 s, estimated 1 s
Ran all test suites.

You can see that the test has been successful.

  • Verification method

Create a new example folder and write it to node JS is used to test the node environment and write to browser Html is used to test the browser environment.

mkdir example
// ./example/node.js
const fegqTestAdd = require('../dist/mytest').add;
console.log(fegqTestAdd(1,2)); // 3

Run node/ example/node. JS, if output 3 indicates that the test is successful.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>browser test</title>
</head>
<body>
    <h2>fegq-test test</h2>
    <script src="../dist/mytest.js"></script>
    <script>
        let result = mytest.add(1,2);
        console.log(result); // 3
    </script>
</body>
</html>

Run live server -- port = 4001 to start an http service, F12 opens the console, and output 3 indicates that the test is successful.

Next, release it to npm.

release

After the package code is written, you can save it to github and then publish it.

  • Pull warehouse initialization content

Here, ssh is used to pull and push the code content, eliminating the links such as user authority verification.

git clone git@github.com:gitguanqi/fegq-test.git

Write a document describing how to use your package.

You can write the cdn address first

https://unpkg.com/

The rules are as follows:

unpkg.com/:package@:version/:file

For example:

https://unpkg.com/jquery@3.6.0/dist/jquery.js

# fegq-test

this is a test package.

## use

+ browser

`<script src="https://unpkg.com/fegq-test@0.0.1/dist/mytest.js"></script>`

+ node

`npm install fegq-test`

Then push it to the warehouse.

git add .
git commit -m "add mytest"
git push origin main

OK, the last step is to release your package.

  • Publish to npm

How to publish public npm packages? My previous article< Node issue command >As already said, I won't repeat it here.

I'll do it directly here.

# Launch publish command
npm publish

# Publish results
npm notice 
npm notice 📦  fegq-test@0.0.1
npm notice === Tarball Contents ===
npm notice 1.1kB LICENSE
npm notice 178B  README.md
npm notice 117B  add.test.js
npm notice 453B  example/browser.html
npm notice 87B   example/node.js
npm notice 64B   index.js
npm notice 218B  lib/index.js
npm notice 879B  package.json
npm notice 642B  webpack.config.js
npm notice === Tarball Details ===
npm notice name:          fegq-test
npm notice version:       0.0.1
npm notice filename:      fegq-test-0.0.1.tgz
npm notice package size:  2.2 kB
npm notice unpacked size: 3.7 kB
npm notice shasum:        2309f87ecd92c1c05cfe01ca1277208c530e483c
npm notice integrity:     sha512-xzksvqJrB7fgQ[...]Azc7jvZ2UXJnQ==
npm notice total files:   9
npm notice
+ fegq-test@0.0.1

Then you can npm I found your bag.

My bag npm address is https://www.npmjs.com/package/fegq-test

common problem

  • cdn address error

I checked here because gitignore file cannot be uploaded from dist directory. Enter the file and delete it.

last

The above is how to publish a package of your own. The browser and node environment are compatible and available.

If there are any deficiencies, you can contact me by email.

Topics: node.js Front-end npm