- Modern JavaScript Web Development Cookbook
- Federico Kereki
- 438字
- 2021-07-02 14:50:02
Working with modules
In the Organizing code in modules section of Chapter 2, Using JavaScript Modern Features, we saw how modern JS works with modules. However, with Node, we have a little setback: it doesn't do modules the modern JS way—unless you are willing to work with experimental features!
Why doesn't Node work with the modern JS modules? The reason harkens back to several years before the new modules with import and export statements existed, and Node implemented the CommonJS module format. (We'll be seeing more about those modules in the next section.) Obviously, libraries meant to be used with Node were also developed using that format, and nowadays there are an uncountable number of modules that follow those guidelines.
However, since the new standard for modules appeared, a pressure began to apply to use the new syntax—but that posed some problems beyond just adjusting the language; can you have two radically different module styles coexisting? (Because, no one can magically transform all the existing code that uses CommonJS into the new format, right?) There are some other differences. ES modules are meant to be used in asynchronous fashion, while CommonJS modules are synchronous; for most cases, this doesn't cause a difference, but there are cases that must be considered.
The solution that was arrived at isn't considered definitive yet. For the time being (since version 8.5) you can enable the ES modules by using the --experimental-modules command line flag. If you invoke node with it, it will recognize the ES modules, if their extension is .mjs instead of plain .js. Hopefully, by version 10, it won't be needed, but that cannot be ensured, and there's also a certain risk that some details might change by then!
So, if I were writing this book in one or two years' time, I'd probably be telling you to just go ahead, start using the .mjs file extension, and use the new style modules.
However, at this time, it should not be considered a totally safe step—the feature is clearly marked as experimental at this point of time—so let's keep going with the current (old) standard, and learn how to work with the old-fashioned modules. Let's create a math module you might want to use for financial coding, so we get to see a Node style module built from scratch.