JS modularization (1): Commonjs

What is modularity?

Answer: A complex program is encapsulated into several blocks according to certain rules and combined together. Its internal data is private, but it exposes some interfaces to the outside to communicate with other external modules.

Why modularize?

  • Reduce complexity
  • Easy to deploy
  • Reduce coupling
  • Avoid naming conflicts

Commonjs modular specification

  • Two of this file are required, one is the package name, and the other is the version number.
  • The package name cannot contain uppercase and Chinese.
  • Automatically generate package.json file
npm init
  • Install uniq
npm install uniq
  • -What does save mean?
    This means to add to package.json

Three ways of commonjs module exposure

1:module.exports = {}

2:module.exports = function()

  • This way of writing is overwriting, the latter will overwrite the former, it is not recommended

3: exports. attributes

  • This is a form of adding attributes to exports, it is recommended to use

4: Install via npm

  • Take the uniq package as an example. This package can filter out the unique elements in the array.
  1. npm install uniq
  2. Import const uniq = require('uniq');
  3. Use const result = uniq(arr);

commonjs is based on the browser-side application

  • First install globally and also need to install browserify locally
npm install browserify -g
npm install browserify --save-dev
  • The browser side cannot accurately identify the require method
  • Need to use browserify for packaging processing
  • The browser is not running our source files, but the packaged files
  • Run successfully at this time

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/114945664