What is the difference between .js and .mjs files?

前端 未结 3 619
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 09:01

I have started working on an existing project based on Node.js. I was just trying to understand the flow of execution, where I encountered with some *.mjs files

相关标签:
3条回答
  • 2021-01-01 09:06

    For clarity. As for devs/humans, it's easy to distinguish between a module file(.mjs) and a normal javascript file(.js)... because it's not always easy to determine even if you examine the code in the file.

    There are also performance benefits which gives you more reason to consider using it. V8(JavaScript engine that powers Google Chrome) recommends the use of .mjs but it still depends on your situation. If you want to know more of it's advantages, check https://v8.dev/features/modules#mjs

    0 讨论(0)
  • 2021-01-01 09:08

    Node.js's native module system is CommonJs.

    It has experimental support for the standard ES6 module system and using a .mjs file extension is part of one way to trigger that support. (As of Node 13, you can trigger support by setting "type": "module", in package.json).

    In short, it is used by Node.js to distinguish between CommonJS and ES6 module files.

    See also: Differences between ES6 module system and CommonJs

    0 讨论(0)
  • 2021-01-01 09:23

    .MJS file

    • mjs an extension for EcmaScript modules
    • An MJS file is a source code file containing an ES Module (ECMAScript Module) for use with a Node.js application.
    • MJS files are written in JavaScript, and may also use the .JS extension outside of the Node.js context.

    • ES Modules allow web and application developers to organize code into smaller reusable components.

    ECMAScript 6 (ES6) introduced the specification for ES Modules, providing a standard for implementing modules in JavaScript. As of 2018, all major web browsers support ES Modules.

    However, the popularity of modularized JavaScript pre-dates ES6. Node.js, a JavaScript runtime environment, used CommonJS as the specification for modules. Because so many existing applications were built with CommonJS, when Node.js added support for native ES modules, it controversially introduced the MJS file extension to differentiate the two and prevent applications from breaking.

    NOTE: Some developers informally refer to MJS files as "Michael Jackson Script" files.

    0 讨论(0)
提交回复
热议问题