Webpack is a JavaScript module bundler. It is widely used in web frameworks, such as React and Angular. This tutorial shows how to implement a simple web barcode reading app with webpack and Dynamsoft JavaScript Barcode library.
Setting Up a Basic Project with Webpack
Create a directory. Initialize the project and install webpack via npm:
mkdir webpack-dbrcd webpack-dbrnpm init -ynpm install webpack --save-devnpm install webpack-cli --save-dev
Create webpack.config.js, src\index.js, and index.html.
Webpack.config.js is the configuration file used for bundling JavaScript modules:
const path = require('path');module.exports = {entry: './src/index.js',output: {path: path.resolve(__dirname, 'dist'),filename: 'bundle.js'}};
The script above takes the ./src/index.js as the entry point and generates a dist/bundle.js as the output. So in index.html, we only need to include dist/bundle.js:
<!doctype html><html><head></head><body><script src="dist/bundle.js"></script></body></html>
Before adding the barcode logic to index.js, let’s build the bundle.js file with the following command:
npx webpack --config webpack.config.js
The npx command is used to execute local npm package binaries. If you have installed webpack globally, you can run:
webpack --config webpack.config.js
Bundling Dynamsoft JavaScript Barcode
Download Dynamsoft JavaScript Barcode library:
npm install dynamsoft-javascript-barcode
Get a free trial license key.
Add the following code to index.js:
Try to run the build. You will see the error message below:
To solve the “ Module not found: Error: Can’t resolve ‘fs’ “ error, open webpack.config.js to add:
const path = require('path');module.exports = {entry: './src/index.js',/////////////////////node: {fs: 'empty'},/////////////////////output: {path: path.resolve(__dirname, 'dist'),filename: 'bundle.js'}};
Now you can successfully build the bundle.js file.
Install Web Server for Chrome to host the project, and then visit the index.html in Chrome.
Oops, error again. There are some files not found. We can use copy-webpack-plugin to copy the dependent files from node modules to the build directory. Install the webpack plugin:
npm install copy-webpack-plugin --save-dev
Add the plugin code in webpack.config.js:
Rebuild the project and refresh the web barcode reader app. It’s working:
Source Code
https://github.com/dynamsoft-dbr/javascript-barcode/tree/master/examples/webpack-dbr
Originally published at https://www.codepool.biz on July 1, 2019.