Js modular is now a more popular use, it can avoid a lot of former JS drawbacks, front-end engineering is involved in the topic, today we come to talk about several modular methods.

The need to introduce multiple JS files to a page causes problems:

  1. Request too much
  2. Relying on the fuzzy
  3. Difficult to maintain These issues can be addressed through modern modular coding and project construction

Modularity benefits:

  • Avoiding naming conflicts (reducing namespace pollution)
  • Better classification, load on demand
  • Higher reusability
  • High maintainability

Several commonly used modularity specifications

1, the commonJs

Commonjs features: Each file can be treated as a module; On the server side: modules are loaded synchronously at runtime; In browser: modules need to be pre-compiled and packaged to handle exposed modules module.exports = values export. XXX = value importing require(XXX) third party modules

  • A simple example running on the server: first, make sure you have NodeJS installed on your computer, because I’m going to use this environment. Commons to create a file, and then build an app in commonjs. Js, establish a modules folder, it respectively built three js file module1. Js, module2, js, module3. Js. Execute the following commands
npm init // Generate a package.json file at the root
Copy the code

module.exports = {
  msg: 'module1',
  fn () {
    console.log(this.msg)
  }
}
Copy the code

module2.js

//module.exports a file can only appear once, otherwise it is easily overwritten by the following
module.exports = function () {
  console.log('module2')}Copy the code

module3.js

exports.fn = function() {
  console.log('fn() module3')
}
exports.bar = function () {
  console.log('bar() module3')}Copy the code

app.js

let module1 = require('./modules/module1')
let module2 = require('./modules/module2')
let module3 = require('./modules/module3')

module1.fn()
module2();
module3.fn()
module3.bar()
Copy the code

Run app.js with Node and the result is shown below

  • Commjs browser-based applications cannot recognize the require in CommJS without the compilation and parsing of tools. For example, we create a commonJS folder, which contains the content as shown in the following figure. Dist file is an empty file created to package the compilation content and put it here. App. Js, module1. Js, module2, js, module3, js is keep up with an example of a content, copy is ok.

    Index.html file is introduced into app.js. When opening index.html in the browser, it does not have the expected preview effect

    We need to install Browserify from the command line with the help of the Browserify tool

npm install browserify -g
npm install browserify -save-dev
Copy the code

And then wrap it up and execute it

browserify src/app.js -o dist/build.js
Copy the code

The index. HTML import file is replaced by a packaged build.js file, which will run normally in the browser.

2、 AMD

Asynchronous module definition, specifically for browser-side module loading is asynchronous

// No dependency modules
define(function (){
  let name = 'dataService.js'
  function getName() {
    return name
  }
  // Expose the module
  return { getName }
}
  );
Copy the code

alerter.js

// Define dependent modules
define([
  'dataService'].function(dataService) {
  let msg = 'alert.js';
  function showMsg() {
    console.log(msg, dataService.getName())
  }
  return {showMsg}
});
Copy the code

main.js

(function() {
// requirejs configuration file configuration
  requirejs.config({
    baseUrl: 'js/'.// Basic path, starting from the root directory
    paths: {
      dataService: './modules/dataService'.alerter: './modules/alerter'}})//
  requirejs(['alerter'].function(alerter){
    alerter.showMsg()
  })
})()
Copy the code

index.html

<! DOCTYPE html><head>
  <meta charset="UTF-8"/>
  <title>test</title>
</head>
<body>
  <script data-main="js/main.js" src="https://cdn.bootcss.com/require.js/2.1.18/require.js"></script>
</body>
</html>
Copy the code

3、 ES6

ES6 modularization is a more popular way at present, but also a trend of future development. Dependent modules need to be compiled and packaged, imported modules use import, and exported modules use export.


qiuqiu$ npm install babel-cli browserify -g
npm install babel-preset-es2015 --save-dev
// Preset (all plugin packages to convert ES6 to ES5)
Copy the code

Define a.babelrc file, which is actually run control.

{
  "presets": ["es2015"]}Copy the code

In es6test build a SRC files and HTML. HTML files under the SRC. Establish the main js, module1. Js, module2. Js module. Js

// Expose modules separately
export function foo () {
  console.log('foo() module1')}export function bar () {
  console.log('bar() module1')}export let arr = [1.2.3.4]
Copy the code

module2.js

function fun () {
  console.log('fun() module2')}function fun2 () {
  console.log('fun2() module2')}export {
  fun,
  fun2
}
Copy the code

main.js

// Introduce additional modules
// Syntax: import XXX from path
import {foo, bar, arr} from './module1'
import {fun, fun2} from './module2'
console.log(foo())
console.log(bar())
console.log(arr)
console.log(fun())
console.log(fun2())
Copy the code

compile

  • Compile ES6 to ES5 code with Babel (but with CO M MMJS syntax) :babel src -d es6test/libThe operation effect is shown as follows:
  • Compile JS with Browserify:
browserify es6test/lib/main.js -o dist/bundle.js 
Copy the code

Finally, run bundle.js from the dist file in index.html to see the effect.

4, CMD

CMD is the standardized output of the module definition in the promotion process of SeaJS. It is a synchronous module definition and a standard of SeaJS. SeaJS is an implementation of CMD concept and SeaJS is aJS framework for module development provided by Alipay team.

conclusion

Today, I mainly share some methods of JS modularization through my own video learning. Some of the above pictures are referenced from the screenshots in the video. If you want to know more, please scan the TWO-DIMENSIONAL code