Skip to content

Commit

Permalink
fix(commonjs): add .cjs to default file extensions. (#524)
Browse files Browse the repository at this point in the history
* 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()
  • Loading branch information
ctjlewis authored Aug 6, 2020
1 parent d9d2900 commit d7f06e9
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/commonjs/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,9 @@ export default function commonjs(options = {}) {
},

transform(code, id) {
if (id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
if (!filter(id) || extensions.indexOf(extname(id)) === -1) {
const extName = extname(id);
if (extName !== '.cjs' && id !== DYNAMIC_PACKAGES_ID && !id.startsWith(DYNAMIC_JSON_PREFIX)) {
if (!filter(id) || !extensions.includes(extName)) {
setIsCjsPromise(id, null);
return null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
test: 42
};
3 changes: 3 additions & 0 deletions packages/commonjs/test/fixtures/samples/cjs-extension/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { test } = require('./export.cjs');

console.log(test);
21 changes: 21 additions & 0 deletions packages/commonjs/test/snapshots/test.js.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,24 @@ Generated by [AVA](https://avajs.dev).
␊
module.exports = main;␊
`

## imports .cjs file extension by default

> Snapshot 1
`'use strict';␊
␊
var _export = {␊
test: 42␊
};␊
␊
const { test } = _export;␊
␊
console.log(test);␊
␊
var main = {␊
␊
};␊
␊
module.exports = main;␊
`
Binary file modified packages/commonjs/test/snapshots/test.js.snap
Binary file not shown.
9 changes: 9 additions & 0 deletions packages/commonjs/test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -639,3 +639,12 @@ test('logs a warning when the deprecated namedExports option is used', async (t)
'The namedExports option from "@rollup/plugin-commonjs" is deprecated. Named exports are now handled automatically.'
);
});

test('imports .cjs file extension by default', async (t) => {
const bundle = await rollup({
input: 'fixtures/samples/cjs-extension/main.js',
plugins: [commonjs()]
});
const code = await getCodeFromBundle(bundle);
t.snapshot(code);
});

0 comments on commit d7f06e9

Please sign in to comment.