JavaScript 世界的模块系统

发布于 2019-06-18 14:47:34

  • The JavaScript language didn’t have a native way of organizing code before the ES2015 standard.
  • Node.js filled this gap with the CommonJS module format.
  • The module system allows you to organize your code, hide information and only expose the public interface of a component using module.exports. Every time you use the require call, you are loading another module.
  • do not use exports = xxx directly, use module.exports = xxx insteadly.

Module is wrapped by Node.js this way

(function (exports, require, module, __filename, __dirname) {
  function add (a, b) {
    return a + b
  }

  module.exports = add
})

This is why you can access the global-like variables like require and module. It also ensures that your variables are scoped to your module rather than the global object.

How does require works

What’s in your node_modules?

  • npm v2: npm 2 installs all dependencies in a nested way, where your primary package dependencies are in their node_modules folder.
  • npm v3: npm3 attempts to flatten these secondary dependencies and install them in the root node_modules folder. This means that you can’t tell by looking at your node_modules which packages are your explicit or implicit dependencies.

ES2015

  • As we saw above, the CommonJS module system uses a runtime evaluation of the modules, wrapping them into a function before the execution.
  • The ES2015 modules don’t need to be wrapped since the import/export bindings are created before evaluating the module. This incompatibility is the reason that currently there are no JavaScript runtime supporting the ES modules.

The structure

  • JS world
    • ECMAScript standards
      • ES5
      • ES6/ES2015
    • TypeScript
  • Other information
    • ES5 is what most of us have used for years. Functional programming at its best, or worst, depending on how you view it. I personally love programming with ES5. All modern browsers support it.
    • ECMAScript 2015 is an ECMAScript standard that was ratified in June 2015.

How to enable ES2015 in nodejs

  • How do we run ES2015 in browsers that do not yet support ES2015? We can use ES2015 and transpile to ES5 using a tool like Babel.

Other module system

References

comments powered by Disqus