简体   繁体   中英

Why do we use ES6 modules for import in frontend frameworks instead of CommonJS

Create-React-App uses Babel that converts my ES6 modules to CommonJS module and Webpack will bundle everything in single file that my browser can understand.

1) Why not use CommonJS modules directly and use Webpack as bundler?

2) Now that ES6 modules are supported in browsers, why don't we transpile React CommonJS modules to ES6 modules.

CommonJS code will not allow you to write code using imports, arrow functions, destructuring, generators, class etc... This makes your developer's life easy and I do see below advantages:

Less code more for same functionality. Less time required for writing same functionality.

As of chrome 61 + can process your ES6 code but other browser will not be supporting it. So you need to transpile ES6 code to common js code so that it is consistent across browsers.

Go to your Chrome console and type in require , you will get the message require not defined .

Our browser, in particular Chrome, has no idea what CommonJS is, it has no idea what modules are.

But if you are looking to remove those restrictions in your project, you can make use of Electron.

If you run require inside of the Electron browser window you will get this:

f require(path) {
  try {
    exports.requireDepth += 1;
    return mod.require(path);
  } finally {
    exports.requireDepth -= 1;
  }
}

Chrome the browser has no idea what the above is, but the Electron browser window does. It has some additional capabilities that Chrome does not.

The Electron browser has a MainWindow object which has access to all the available modules the belong to the Nodejs runtime and access to all modules inside the browser as well. So access to CommonJS as well as fs, crypto, etcetera.

You can do `require('fs') and access the filesystem directly from the Electron browser console.

In short, I am saying that with Electron you can directly require in modules like you want without having to use Webpack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM