Using JavaScript modules in browsers 1:Using JS modules in browsers

brief introduction

Now, all mainstream browsers already support JS modules (Chrome, Edge, Safari, Firefox)~This article will explain how to use JS modules in browsers, how to deploy them responsibly, and how the Chrome team works hard to make JS modules better.

What is a JS module

JS module (also known as ES module or ECMAScript module) is a major new feature, or a series of new features. You may have already used third-party module loading systems. CommonJs such as nodeJs, AMD such as requestJs, and so on. These module loading systems all have one thing in common: they allow you to perform import and export operations.

JavaScript has now developed a standard syntax for modularity. With the JS module, you can use the export keyword to export anything. You can export const, function, or any other variable binding or declaration. All you need to do is add an export before declaring the variable or use export to declare it.

You can use import to import modules from any other module. Here, we introduce the repeat and shoot methods from the lib module and use them in the main module (the current module).

You can also use export default to export a default value from the module.

The module exported with export default can be imported with any name in other modules.

There are some differences between JS modules and regular JS scripts:

  • The module defaults to strict mode (stick module)
  • HTML style annotations are not supported
  • The module has its own scope. This means that using var foo=42 in the module does not create a global variable foo and cannot be accessed through window.foo. This is different from regular JavaScript scripts
  • The export and import keywords can only be used in modular systems, so they cannot be used in regular JavaScript scripts

Due to these differences, when the same JavaScript script is executed as a JS module and a regular JavaScript script, there may be different behavioral behaviors. So, the JavaScript runtime environment must know if the introduced script is a JS module.