How to use npm modules in HTML?
Background
The company's j2ee system now needs to upgrade some front-end functions, and some modules on npm are needed. Since the system is basically developed with jsp, it is impossible to separate the front and back ends, and front-end tools such as webpack cannot be used, so Browserify+uglify-js is needed to convert the npm library into bundle.js that can be directly referenced by HTML.
Installation
Install Browserify and uglify-js
npm install -g browserify
npm install -g uglify-js
npm install -g esmify
npm install -g browser-resolve
Create an npm project
Create an npm project locally with default settings
mkdir myproject
cd myproject
npm init
Install the npm packages you need to use, such as the two libraries remark
and remark-docx
in our project
npm install --save remark
npm install --save remark-docx
If the npm package used is a pure esm module, you need to add it to package.json
"type": "module"
Create main.js
to call the npm library in js and export it to window
import { unified } from "unified";
import markdown from "remark-parse";
import docx from "remark-docx";
var processor = unified().use(markdown).use(docx, { output: "blob" });
//Export the main program of the library to the window
window.myprocess = processor
Package bundle.js
browserify will convert all npm packages used by main.js into js that can also be used in the browser environment. If the project has esm modules, you need to add the -p esmify
parameter. If not, it is not necessary.
browserify main.js -p esmify > bundle.js
The bundle.js generated by browserify packaging is still relatively large and needs to be compressed. Here we use uglifyjs for compression
uglifyjs bundle.js -m -o bundle-min.js -c
bundle-min.js can be placed in html and imported with script tags. Create a test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<script src="bundle-min.js"></script>
<script>
const text = "# hello world";
<!--window.myprocess is the main program of the library we exported -->
console.log(window.myprocess)
</script>
</body>
</html>
Others
Uglifyjs other parameter descriptions
-o,--output specifies the output file, which is the command line by default
-b,--beautify the parameters for beautifying the code format
-m,--mangle changes the variable name (ex: in some YUI After Compressor compresses the code, you can see variables such as a, b, c, d, e, and f. Uglifyjs can also do this with the -m parameter. By default, the variable names will not be changed.)
-r, --reserved Reserved variable names do not need to be changed by the -m parameter
-c, --compress OK, the protagonist appears. This is the parameter for uglifyjs to compress the code. You can add it after -c
--comments is used to control the commented code