Что такое формат файла MJS?
Файл .mjs - это исходный код JavaScript, который Node.js загружает как модуль ECMAScript (ESM). Расширение служит сигналом: любой файл, заканчивающийся на .mjs, обрабатывается как модуль ES с использованием операторов import и export, даже если в package.json проекта ничего не сказано о типе модуля.
Node.js добавил это расширение в версии 8.5.0 (2017), сначала под флагом --experimental-modules, и сделал его стабильным в версии 12. Оно существует для разделения двух систем модулей. Старый код Node использует CommonJS с require() и module.exports, а современный код использует ESM. Обычный файл .js по умолчанию считается CommonJS, поэтому .mjs дает однозначный способ перехода на модули. Соответствующее расширение .cjs принудительно активирует CommonJS в обратном порядке.
Код в файле .mjs автоматически запускается в строгом режиме (strict mode) и может использовать await на верхнем уровне и объект import.meta, что не работает в CommonJS. Сборщики, такие как webpack, Rollup и Vite, умеют как читать, так и записывать файлы .mjs.
Безопасность и защита
РИСК: MEDIUMAn .mjs file is executable JavaScript. Running one with node executes whatever code it contains, so an untrusted .mjs file can perform harmful actions such as reading files or making network requests. Opening it in a text editor is safe; only run .mjs files from sources you trust, and review the code first.
Детали формата
в двух словах- Generic minified JavaScript module - Some build tools emit .mjs to mark a bundled or minified ES module output rather than a hand-written source file.
Программы, открывающие файлы MJS
Технические подробности
глубокая спецификация| Encoding | UTF-8 plain text |
| Byte order | Not applicable (text file, no byte-order dependence; BOM optional but discouraged) |
| Container | None; raw JavaScript source |
| Typical size | A few hundred bytes to tens of kilobytes per module |
| Structure | Human-readable JavaScript source using the ECMAScript module system. Uses static import and export statements, supports top-level await and import.meta, and runs in strict mode by default. Each .mjs file is a module with its own top-level scope; variables are not shared globally. |
| Integrity | None built in; integrity is handled externally (npm package hashes, Subresource Integrity on the web, git). |
| Platforms | Windows, macOS, Linux, BSD, any OS running Node.js or a modern browser |
| Notes | Node.js treats any .mjs file as an ES module regardless of the package.json "type" field, which is the main reason the extension exists. The counterpart .cjs forces CommonJS. Browsers can also load .mjs via <script type="module"> provided the server sends a JavaScript MIME type. Bundlers such as webpack, Rollup, esbuild and Vite read and emit .mjs. |
| Runs In | Node.js runtime and modern web browsers (via script type=module) |
| Strict Mode | Always enabled; ES modules run in strict mode automatically |
| Выпущен | 2017 (Node.js v8.5.0) |
| Последняя версия | ECMAScript 2015 module system (stabilized in Node.js v12+) |
| Открыть стандартное | Да · без роялти |
| Спецификация | nodejs.org |
Конвертации MJS
Вопросы и ответы сообщества
спрошено пользователямиВопросов пока нет - станьте первым, кто спросит о файлах MJS.