Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

background

  • Front-end modules are closely related to The Times. Long ago, JS did not have a module system, which meant that large programs could not be broken down into interdependent small files and assembled again.

  • The main module specification used before ES6 (ES2015)

    • CommonJS is used on servers and features synchronous loading, but the downside is that the front end is unfriendly and synchronization means blocking
    • AMD and CMD are used in browsers, but THE development cost of AMD is high, the code is difficult to read, and the loading logic of CMD module is too heavy
  • After the ES6

    • Module idea: try to be static, so that the dependencies, output and input variables of the module can be determined at compile time; Both CommonJS and AMD modules can only determine this at run time. (For example: CommonJS modules are objects and must look for object properties when entering)
    • ES6 implements module functions on the level of language standards. However, up to now, all kinds of browser engines have not fully implemented ES6. At present, we need to use BABEL tool and convert it to ES5, which leads to the mixing of import and module.exports, require and export in our development
  • This article mainly discusses, what should pay attention to when mixing? How should the server be used? How to mix pure front-end JS modules (with webpack-build)?

Question: answer at the end of the article

  • React, Vue, and element-UI export default can be destructed during import.
  • Front-end development ES6 syntax standard, why can mix require? module.exports? What should I pay attention to when introducing?
  • Relationship between Node and ES6?
  • Webpack tree-shaking what?
  • Can the use of es6/index.js require in app-API be replaced with import? Why is that?
  • How to develop NPM packages supported by both Node and ES6 environments?

The module specification

CommonJS module specification

  • Each file is a module with its own scope. Variables, functions, and classes defined in the file are private and invisible to other files
  • Node follows the CommonJS module specification
    • Node provides an exports variable (an interface to the outside) for each module, pointing to module.exports
// In the header of each module, there is a line of command like this
var exports = module.exports;
Copy the code
  • The module has the following attributes
moduleId The module identifier, usually the module file name with an absolute path.moduleFilename specifies the filename of the module with an absolute path.module.loaded Returns a Boolean value indicating whether the module has completed loading.module.parent returns an object representing the module that called the module.module.children returns an array representing other modules used by this module.module.exports indicates the value that the module exports.Copy the code
  • Note: You cannot point the exports variable to another value

  • Module exports: require, which loads the module’s module.exports property

    • Require loading mechanism: Input is a copy of the output value. Once a module outputs a value, changes within the module do not affect the output value
    • TODO require internal processing

ES6 module specifications

  • Default is an ES6 unique keyword
  • Export default specifies the default output for the module, which can only be used once
  • Export const XXX is output separately and can be used multiple times

Common combination mode

import

  • Import and export const XXX
//export.js
export const obj = { name: 'module'};
 
//index.js
import { obj } from './export';
console.log(obj.name); //module
 
import * as customObj from './export';
console.log(customObj.name); //module
Copy the code
  • The import and export of default
//export.js
export default { name: 'module'};
 
//index.js
import obj from './export';
console.log(obj.name); //module
// Error
import { name } from './export';
Copy the code
  • The import and the module exports
//export.js
module.exports = { name: 'module' };
 
//index.js
import { name } from './export';
console.log(name); //module
 
import customObj from './export';
console.log(customObj.name); //module
Copy the code

require

  • The require with the module. Exports
//export.js
mocule.exports = { name: 'module'};
 
//index.js
const exportsObj = require("./export");
console.log(exportsObj.name); //module
Copy the code
  • Require and export const XXX
//export.js
export const obj = { name: 'module' };
 
//index.js
const { exportObj }| = require("./export");
console.log(exportObj.name); //module
Copy the code
  • The require and export defalut
//export.js
export default { name: 'module' };
 
//index.js
const { exportObj }| = require("./export").default;
console.log(exportObj.name); //module
Copy the code

TODO Webpack modular parsing

The principle of WebPack and Babel

Wrong usage

  • Grammar mistakes
//exoprt.js
export 1;
//export.js
const obj = { name: 'module' };
export obj;
 
// Cause of the above error: there is no external interface, direct output value, not interface
// The essence of exporting is that there is a one-to-one relationship between interface names and internal variables
//export.js
export default const obj = { name: 'module' };
 
// Cause of the above error: Attempting to redefine the default variable
Copy the code
  • In the same module
//export.js
import { a } from './export.js';
module.exports = {
    name: a
}
 
//export.js
// exports is disconnected from Module. exports
exports = (param) = > { / /... }
 
SayHello cannot export because module.exports was reassigned
exports.sayHello = function() {
  return 'hello'
}
 
module.exports = 'Hello world'
Copy the code

# Not recommended usage

  • Module.exports appears in pure front-end module files
  • The Node application’s module assigns or modifies its reference to exports alone

The answer

  • Most of these open source packages are packaged as Commonejs compliant packages or UMD-type packages
  • Pure front-end engineering using ES6 as the module standard, is webpack to help us implement require
  • NodeJS 9.0+ supports ES6 module standards
  • Tree -shaking automatically detects and statically analyzes unused code modules, as long as you use ES6 standard modules
  • Instead, app-API environment variables are browser-side run-time judgments, there is no tree-shaking optimization, modules are packaged and output to the browser
  • The WebPack export specifies Library and libraryTarget

To sum up

  • Be aware of the operating environment during development
  • Don’t mix CommoneJs with ES6
  • When developing multi-terminal support NPM package, please do module design first

Praise support, hand left lingering fragrance, with rongyan, move your rich little hands yo, thank you big guy can leave your footprints.

Past wonderful recommendation

Front-end common encryption methods

Canvas Pit Climbing Road

Don’t know SEO optimization? An article helps you understand how to do SEO optimization

Canvas Pit Road

Wechat small program development guide and optimization practice

Talk about mobile adaptation

Front-end performance optimization for actual combat

Talk about annoying regular expressions

Obtain file BLOB stream address to achieve the download function

Vue virtual DOM confused? This article will get you through the virtual DOM once and for all

Git Git

Easy to understand Git introduction

Git implements automatic push

Interview Recommendations

Front ten thousand literal classics – the foundation

Front swastika area – advanced section

More exciting details: personal homepage