detect whether ES Module is run from command line in Node

Use if (import.meta.url === `file://${process.argv[1]}`) { // module was not imported but called directly } See the MDN docs on import.meta for details. Update Sep 27, 2021 Perhaps more robust, but involving an extra import (via Rich Harris) import { pathToFileURL } from ‘url’ if (import.meta.url === pathToFileURL(process.argv[1]).href) { // module was not imported but … Read more

Import ‘.json’ extension in ES6 Node.js throws an error

From Node.js version 17.5.0 onward, importing a JSON file is possible using Import Assertions: import packageFile from “../../package.json” assert { type: “json” }; const { name, version } = packageFile; assert { type: “json” } is mandatory Destructuring such as { name, version } is not possible in the import declaration directly The contents of … Read more

Import ES module in Next.js ERR_REQUIRE_ESM

From Next.js 12, support for ES Modules is now enabled by default, as long as the ESM library has “type”: “module” in its package.json. Using next-transpile-modules to transpile ESM libraries is no longer required. Before Next.js 12 Since ky is exported as ESM you can transpile it with next-transpile-modules in next.config.js. // next.config.js const withTM … Read more

ES2015 “import” not working in node v6.0.0 with with –harmony_modules option

They’re just not implemented yet. Node 6.0.0 uses a version of V8 with most of ES6 features completed. Unfortunately modules isn’t one of those completed features. node –v8-options | grep harmony in progress harmony flags are not fully implemented and usually are not working: –es_staging (enable test-worthy harmony features (for internal use only)) –harmony (enable … Read more

how to reset module imported between tests

You have to re-import or re-require your module. Check the doc or this issue for more information: https://github.com/facebook/jest/issues/3236 https://facebook.github.io/jest/docs/en/jest-object.html#jestresetmodules describe(‘MyModule’, () => { beforeEach(() => { jest.resetModules() }); describe(‘init’, () => { const myModule = require(‘./MyModule’); it(‘not throws exception when called’, () => { expect(() => myModule.init()).not.toThrow(); }); }) describe(‘do’, () => { const myModule … Read more