#Issue with cjs file not having cjs extension

1 messages · Page 1 of 1 (latest)

fallen arch
#

Not sure if this is to be considered an issue on my end, for remix.js or with vite, so I wanted to ask:

I have a UI component library which compiles into one index.js (ESM) and index.cjs.js (CJS). I declare them both respectively in my package.json via the "main" and "module" properties. Now, when trying to use the library in Remixjs, I get an error "[vite] Internal server error: require is not defined in ES module scope, you can use import instead. This file is being treated as an ES module because it has a '.js' file extension and '/Users/oes0003t/Projects/tom/y/node_modules/@schedule-x/react/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension."

The most important part here, I believe, is "To treat it as a CommonJS script, rename it to use the '.cjs' file extension." Because this is true, when I change my build output filename into index.cjs instead of index.cjs.js it magically resolves it as CJS and everything works.

My question is: should this really be? I've seen other libraries compile CJS into {filename}.cjs.js before, and it kind of surprises me that it would be expected of me to break with this naming.

Any thoughts or insights?

warm walrus
#

You need the explicit .cjs extension. It's how node tells cjs/esm apart

fallen arch
fallen arch
#

And what I also can't grasp is how it works in a Nextjs setup without the .cjs extension, though Node is at work there too

warm walrus
#

The main option doesn't necessarily needs to point to CJS code. It can point to ESM too. In which case, node uses the .cjs or type: 'commonjs' hueristic to determine if it's cjs/esm