Webpack is a module packaging tool that can translate simple syntax such as import. In addition to the ES Moudule specification (import), it can also recognize modular syntax such as CommonJS, CMD, AMD, etc.

One, the use of modular example

1.1 Usage of ES Moudule

Other module file export content

/ / headers. Js file

function Header () {
  let root = document.getElementById('root');
  let ele = document.createElement('div');
  ele.innerHTML = 'This is the head.'
  root.append(ele);
}
export default Header;

/ / footer. Js file
function Footer () {
  let root = document.getElementById('root');
  let ele = document.createElement('div');
  ele.innerHTML = 'This is the bottom two'.
  root.append(ele);
}
export default Footer;
Copy the code

Import the required modules into the index.js file

import Header from './header';
import Footer from './footer';

Header();
Footer();
Copy the code

1.2 Usage of Commonjs

Other module file export content

/ / headers. Js file

function Header () {
  let root = document.getElementById('root');
  let ele = document.createElement('div');
  ele.innerHTML = 'This is the head.'
  root.append(ele);
}
module.exports = Header;

/ / footer. Js file
function Footer () {
  let root = document.getElementById('root');
  let ele = document.createElement('div');
  ele.innerHTML = 'This is the bottom two'.
  root.append(ele);
}
module.exports = Footer;
Copy the code

Import the required modules into the index.js file

let Header = require('./header');
let Footer = require('./footer');

Header();
Footer();
Copy the code

Webpack packs instances

By default, a dist/main.js file is generated once the packaging is complete

2.1. Package instance of ES Moudule introduced

$NPX webpack./es/index.js [webpack-cli] Compilation finished Hash: 4c44f5ae0586d9af15 Version: Webpack 4.44.2 Time: 472ms Built at: Emitted emitted by Asset Size Names main.js 1.31 KiB 0 [emitted by] main Entrypoint main = main.js [0] ./es/index.js + 3 modules 811 bytes {0} [built] | ./es/index.js 123 bytes [built] | ./es/header.js 228 bytes [built] | ./es/side.js 230 bytes [built] | ./es/footer.js 230 bytes [built]Copy the code

2.2 Packaging instance of Commonjs introduction

$ npx webpack ./commonj/index.js [webpack-cli] Compilation finished Hash: d0649da5dbdf7df222d7 Version: Webpack 4.44.2 Time: 463ms Built at: 2020/11/05 morning 12:13:37 Asset Size Chunks Chunk Names. The main js 1.38 KiB 0 [emitted] main Entrypoint main. = the main js [0] ./commonjs/index.js 132 bytes {0} [built] [1] ./commonjs/header.js 230 bytes {0} [built] [2] ./commonjs/side.js 232 bytes {0} [built] [3] ./commonjs/footer.js 233 bytes {0} [built]Copy the code