Search code examples
javascriptpackage.jsones6-modules

Exclude files from type: module without changing file extension


I had to set "type": "module" in my package.json file and I would like to exclude some files from being treated as ES module files but WITHOUT changing its extension, as I need to keep it as .js file because other server scripts, (which I cannot change) points directly to that specific filename.js file and not .cjs or any other extension - is it possible via some config files?


Solution

  • As far as I know, for what you've described you only have a couple of options (some of which, or possibly all of which, may not work for your specific situation):

    • Don't use "type": "module" (so the files that have to be CommonJS remain CommonJS) and instead rename the files you want handled via ESM to .mjs.
    • Ensure that a different package.json applies to the files you want handled as CommonJS modules, for instance by putting them in a scripts subdirectory with a package.json that has {"type": "commonjs"} in it. (But if you can't change the file extensions on the files to .cjs, you probably can't move them to another folder.)
    • Create your own module loader that delegates the loading of these files to the CommonJS loader while loading others via ESM. (Not a small thing, but not impossible either; here's an example of onefrom back before Node itself supported ESM.)