Skip to content

Commit d7f06e9

Browse files
authored
fix(commonjs): add .cjs to default file extensions. (#524)
* Added .cjs and .mjs to default file extensions. * Removed accidental yarn.lock. * Added test. * Added snapshots. * Removed unneeded extension. * Moved extension check, refactored Array.indexOf() to Array.includes()
1 parent d9d2900 commit d7f06e9

File tree

6 files changed

+39
-2
lines changed

6 files changed

+39
-2
lines changed

β€Žpackages/commonjs/src/index.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -188,8 +188,9 @@ export default function commonjs(options = {}) {
188188
},
189189

190190
transform(code, id) {
191-
if (id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
192-
if (!filter(id) || extensions.indexOf(extname(id)) === -1) {
191+
const extName = extname(id);
192+
if (extName !== '.cjs' && id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
193+
if (!filter(id) || !extensions.includes(extName)) {
193194
setIsCjsPromise(id, null);
194195
return null;
195196
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
test: 42
3+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const { test } = require('./export.cjs');
2+
3+
console.log(test);

β€Žpackages/commonjs/test/snapshots/test.js.md

+21
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,24 @@ Generated by [AVA](https://avajs.dev).
2121
␊
2222
module.exports = main;␊
2323
`
24+
25+
## imports .cjs file extension by default
26+
27+
> Snapshot 1
28+
29+
`'use strict';␊
30+
␊
31+
var _export = {␊
32+
test: 42␊
33+
};␊
34+
␊
35+
const { test } = _export;␊
36+
␊
37+
console.log(test);␊
38+
␊
39+
var main = {␊
40+
␊
41+
};␊
42+
␊
43+
module.exports = main;␊
44+
`
77 Bytes
Binary file not shown.

β€Žpackages/commonjs/test/test.js

+9
Original file line numberDiff line numberDiff line change
@@ -639,3 +639,12 @@ test('logs a warning when the deprecated namedExports option is used', async (t)
639639
'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
640640
);
641641
});
642+
643+
test('imports .cjs file extension by default', async (t) => {
644+
const bundle = await rollup({
645+
input: 'fixtures/samples/cjs-extension/main.js',
646+
plugins: [commonjs()]
647+
});
648+
const code = await getCodeFromBundle(bundle);
649+
t.snapshot(code);
650+
});

0 commit comments

Comments
Β (0)