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. I have searched the web where I found that these are module based JS-files.
I want to know how is it different from *.js files (how does it benefit)?
It indicates an ES6 module file.
Node.js's original module system is CommonJs (which uses require and module.exports).
Since Node.js was created, the ECMAScript module system (which uses import and export) has become standard and Node.js has added support for it.
Node.js will treat .cjs files as CommonJS modules and .mjs files as ECMAScript modules. It will treat .js files as whatever the default module system for the project is (which is CommonJS unless package.json says "type": "module",).
See also: Differences between ES6 module system and CommonJs
.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.
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
Related
I was considering updating my Node/Express code to use import instead of require by adding to my package.json file the line:
"type": "module",
However, I did not know why most Node/Express code I see, still uses require while code I see in the browser via webpack uses import.
Is there a reason for this duality? Is upgrading to import recommended in general? Is import because it is newer considered an upgrade and a better technology?
This previous Q/A is over 7 years old and has lot of historical information. I am looking for more current information as the language has evolved.
The reason for having two types of modules is purely historical.
Back in 2009 when Node.js was created, ES modules (import syntax) did not exist yet, but there existed other nonstandard alternatives, with the most important being AMD and CommonJS, for which several browser implementations were available. Node.js decided to adopt CommonJS (require syntax). For this reason, all packages deployed up until 2015 are CommonJS packages.
Native ES modules were introduced with the ECMAScript 2015 standard, but they only made it as an experimental technology in Node.js 8.5 in 2017, and it wasn't until Node.js 12 (2019) that their support became good enough to place them as an alternative to CommonJS (although this is subjective).
For this reason, a large part of software developed for Node.js still uses CommonJS modules with require statements.
Whether ES modules are better is a matter of opinion, and not a proper question for StackOverflow. At least, they are standard JavaScript, which makes them fit for use both in browsers and in Node.js, which is imo a big advantage.
A disadvantage is that ES modules cannot be required in CommonJS code - the opposite is true: CommonJS modules can be imported by ES modules - so if any of your dependencies uses ES modules, that may be a good opportunity to switch your code to ES modules, too.
So should we upgrade to use import in general? Of course, that's also a matter of opinion. And if that was my opinion, the answer would be "no", because there is no reason to change a running system. CommonJS code is not going to rust or worsen simply because a better alternative exists nowadays, although ES modules are a better choice for new code. Node.js, as long as people use it, is not going to drop support for CommonJS either.
There is a project called Deno which is designed to provide a more modern and secure alternative to Node.js to run JavaScript code on the server. Deno was originally designed to work with ES modules only, but it soon became clear that not supporting CommonJS modules was a major issue, because so many npm packages were not working, so it introduced a compatibility mode to support CommonJS modules under a flag. The moral of the story is: removing support for require is good idea, but re-adding it is an even better one.
I am unsure the differences between importing a JavaScript module in the following:
CommonJS
ES5
ES6
NodeJS
Typescript
Why are there so many ways to import javascript modules? Is "module" defined differently in different implementations? Are all doing the same thing but with different syntax?
There are no modules in ES5 and earlier. Various module systems (CommonJS, AMD, and the CommonJS-like ones in and Node.js and TypeScript) were created because there was no standard module system in JavaScript at the time, but it's a really useful thing to have. So the need got filled by tools and toolbuilders.
ES2015 (aka "ES6") created a standard syntax for modules in JavaScript which has now been adopted by all modern browsers, Node.js, and TypeScript. That standard syntax leaves the semantics of module identifiers up to the host environment, so leaders in the web community had to come to consensus for how to do them in browsers (and Node.js had to figure out how to do it in Node.js, etc.), so there was a bit of a delay between ES2015 coming out and your being able to use that syntax natively (though Webpack, Rollup, and such handled it).
There are some use cases where ES2015's static syntax doesn't quite do the job, so there's the import() (dynamic import) proposal which is already supported in some environments and will be in ES2020.
I've been looking all over the Internet without a clear answer for this.
Currently Node.js uses only CommonJS syntax to load modules, and if you really want to use the standard ECMAScript 2015 modules syntax, you either have to transpile it beforehand or use an external module loader at runtime.
Currently I'm not too positive to use either of those two methods, are the Node.js maintainers even planning to support ECMAScript 2015 modules or not? I haven't found an hint at all about this.
At the moment Node.js 6.x claims to support 96% of the ECMAScript 2015 features, but there isn't any reference to modules (Node.js ECMAScript 2015 support link).
Do you know if Node.js will support these modules out of the box, in the near future?
Node.js 13.2.0 & Above
Node.js 13.2.0 now supports ES Modules without a flag 🎉. However, the implementation is still marked as experimental so use in production with caution.
To enable ECMAScript module (ESM) support in 13.2.0, add the following to your package.json:
{
"type": "module"
}
All .js, .mjs (or files without an extension) will be treated as ESM.
There are a number of different options other than entire package.json opt-in, all of which are detailed in the documentation for 13.2.0.
Node.js 13.1.0 & Below
Those still using older versions of Node may want to try the [esm][3] module loader, which is a production-ready implementation of the ES Modules Specificaiton for Node.js:
node -r esm main.js
Detailed Updates...
23 April 2019
A PR recently landed to change the way ECMAScript modules are detected:
https://github.com/nodejs/node/pull/26745
It's still behind the --experimental-modules flag, but there are major changes in the way modules can be loaded:
package.type which can be either module or commonjs
type: "commonjs":
.js is parsed as CommonJS
the default for an entry point without an extension is CommonJS
type: "module":
.js is parsed as an ECMAScript module
does not support loading JSON or a native module by default
the default for an entry point without an extension is ECMAScript module
--type=[mode] to let you set the type on entry point. Will override package.type for entry point.
A new file extension .cjs.
this is specifically to support importing CommonJS in the module mode.
this is only in the ECMAScript module loader, the CommonJS loader remains untouched, but the extension will work in the old loader if you use the full file path.
--es-module-specifier-resolution=[type]
options are explicit (default) and node
by default our loader will not allow for optional extensions in the import, the path for a module must include the extension if there is one
by default our loader will not allow for importing directories that have an index file
developers can use --es-module-specifier-resolution=node to enable the CommonJS specifier resolution algorithm
This is not a “feature”, but rather an implementation for experimentation. It is expected to change before the flag is removed
--experimental-json-loader
the only way to import JSON when "type": "module"
when enable all import 'thing.json' will go through the experimental loader independent of mode
based on whatwg/html#4315
You can use package.main to set an entry point for a module
the file extensions used in main will be resolved based on the type of the module
17 January 2019
Node.js 11.6.0 still lists ES Modules as experimental, behind a flag.
13 September 2017
Node.js 8.5.0 has been released with support for mjs files behind a flag:
node --experimental-modules index.mjs
The plan for this is to remove the flag for the v10.0 LTS release.
--Outdated Information. Kept here for historical purposes--
8 September 2017
The Node.js master branch has been updated with initial support for ESM modules:
https://github.com/nodejs/node/commit/c8a389e19f172edbada83f59944cad7cc802d9d5
This should be available in the latest nightly (this can be installed via nvm to run alongside your existing install):
https://nodejs.org/download/nightly/
And enabled behind the --experimental-modules flag:
package.json
{
"name": "testing-mjs",
"version": "1.0.0",
"description": "",
"main": "index.mjs" <-- Set this to be an mjs file
}
Then run:
node --experimental-modules .
February 2017:
An Update on ES6 Modules in Node.js
The Node.js guys have decided that the least bad solution is to use the .mjs file extension. The takeaway from this is:
In other words, given two files foo.js and bar.mjs , using import * from 'foo' will treat foo.js as CommonJS while import * from 'bar'
will treat bar.mjs as an ES6 Module
And as for timelines...
At the current point in time, there are still a number of
specification and implementation issues that need to happen on the ES6
and Virtual Machine side of things before Node.js can even begin
working up a supportable implementation of ES6 modules. Work is in
progress but it is going to take some time — We’re currently looking
at around a year at least.
October 2016:
One of the developers on Node.js recently attended a TC-39 meeting and wrote up a superb article on the blockers to implementing for Node.js:
Node.js, TC-39, and Modules
The basic take-away from that is:
ECMAScript modules are statically analyzed, and CommonJS are evaluated
CommonJS modules allow for monkey-patching exports, and ECMAScript modules currently do not
It's difficult to detect what is an ECMAScript module and what is CommonJS without some form of user input, but they are trying.
*.mjs seems the most likely solution, unless they can accurately detect an ECMAScript module without user-input
-- Original Answer --
This has been a hot potato for quite some time. The bottom line is that yes, Node.js will eventually support the ES2015 syntax for importing/exporting modules - most likely when the specification for loading modules is finalized and agreed upon.
Here is a good overview of what's holding Node.js up. Essentially, they need to make sure that the new specification works for Node.js which is primarily conditional, synchronous loading and also HTML which is primarily asynchronous.
Nobody knows for sure right now, but I imagine Node.js will support import/export for static loading, in addition to the new System.import for dynamic loading - while still keeping require for legacy code.
Here's a few proposals on how Node might achieve this:
In defense of .js
.mjs modules
I know that if there are multiple JS files to be rendered by the browser, which apparently have identifiers inside, the global scope is polluted by this identifiers. I also know that one way to avoid this is using modules which(in my understanding) are just objects which have the aformentioned identifiers as members, thus sort of imitating C++ namespaces. I am also learning Node.js and there is a built in module system which eases this task so my question is: how to use modules in js files that are sent to the browser to be rendered?
Thanks.
Tools like browserify and WebPack are exactly what you are looking for (I personally prefer browserify over WebPack). Have a look at this answer, it explains a lot of your concerns.
In Node.JS, you can export a module using module.exports keyword, but you cannot just import those modules in your browser by just requiring them in a <script> tag. That's because, the browser doesn't understand the module system and everything works in the context of a global window object there, so module.exports simply becomes window.module.exports which I'm sure you'll not want. Hence you use tools like browserify that process the Node.JS scripts into something that your browser will understand.
This problem is usually solved by module bundlers or module loaders (e.g Webpack, Browserify, RequireJS). They are able to understand relations between your JS modules, skip unused modules and produce output that just works in your browser. All of that without the need to worry too much about global scope if you follow some conventions.
Some time ago, before ES6, two different approaches to this problem were widely used:
CommonJS:
var module = require('my-module');
widely known from Node.js
AMD:
define(['jquery'] , function ($) {
return function () {};
});
Which was suited for browser usage since it by design supported asynchronous loading of modules.
Then ES6 was introduced with native support for modules:
import * as lib from 'lib';
Main problem with new technology in web is that you often have variety of browsers to support which for a long time prevented developers from using new features. Nowadays, we have code transpilers and sophisticated code bundlers (e.g. Webpack). With their help you can use latest version of language, compile and bundle your code and at the end single "bundle.js" file is emitted which supports older browsers at the cost of slower execution times.
I've got a browserify javascript project, where I include modules with the require statement. I'm now adding in some typescript, and it's working fine when I simply require the compiled javascript.
But typescript also has its own module statement. How does this relate to browserify/node's modules? Should I be using both? That seems redundant. Which type of modules should be used, and under what circumstances?
Thanks.
In newer versions of TypeScript (1.5) the module is deprecated in favour of namespace keyword. The keyword is to be used to create internal modules - allows you to organise your code internally.
So now it is more obvious that those are different things. Still TypeScript provides ability to create browserify/node's modules - external modules. For that you can use ES6 module syntax or older TypeScript's syntax. Then use browserify plugin (such as tsify) for more convenient builds.
More documentation about TypeScript modules and namespaces can be found here (also describing the older external modules syntax)
Which type of modules should be used depends on the project and taste of developers. If you target Node.js it worth to use CommonJS modules (IMHO ES6 syntax in TS and transpile it to CommonJS). If you are using browserify it is reasonable to use external modules, too. Namespaces is recommended to use only inside one file - hence internal modules.