Skip to content

Commit ee4ba0f

Browse files
committed
feature(@putout/plugin-convert-esm-to-commonjs) add support of async function
1 parent f029076 commit ee4ba0f

File tree

4 files changed

+50
-1
lines changed

4 files changed

+50
-1
lines changed

packages/plugin-convert-esm-to-commonjs/lib/convert-esm-to-commonjs.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
'use strict';
22

3+
const {template} = require('putout');
4+
35
module.exports.report = () => 'Commonjs should be used insted of ESM';
46

57
module.exports.replace = () => ({
68
'export default __a': 'module.exports = __a',
79
'export class __a {}': 'module.exports.__a = class __a {}',
8-
'export function __a(__args) {}': 'module.exports.__a = function __a(__args) {}',
10+
'export function __a(__args) {}': replaceFn,
11+
'export async function __a(__args) {}': replaceFn,
912
'export const __a = __b': 'module.exports.__a = __b',
1013

1114
'import "__a"': 'require("__a")',
@@ -25,3 +28,12 @@ module.exports.replace = () => ({
2528

2629
});
2730

31+
function replaceFn({__a}, path) {
32+
const {name} = __a;
33+
const {declaration} = path.node;
34+
const node = template.ast.fresh(`module.exports.${name} = __x`);
35+
36+
node.right = declaration;
37+
38+
return node;
39+
}

packages/plugin-convert-esm-to-commonjs/test/convert-esm-to-commonjs.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,8 @@ test('plugin-convert-esm-to-commonjs: transform: import specifier', (t) => {
5555
t.end();
5656
});
5757

58+
test('plugin-convert-esm-to-commonjs: transform: export function', (t) => {
59+
t.transform('export-function');
60+
t.end();
61+
});
62+
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
module.exports.findMadrun = async function findMadrun(cwd) {
2+
const madrunNames = [
3+
'.madrun.js',
4+
'.madrun.mjs',
5+
'.madrun.cjs',
6+
].map(joinPartial(cwd));
7+
8+
for (const name of madrunNames) {
9+
const [error] = await tryToCatch(access, name);
10+
11+
if (!error)
12+
return name;
13+
}
14+
15+
return '';
16+
};
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export async function findMadrun(cwd) {
2+
const madrunNames = [
3+
'.madrun.js',
4+
'.madrun.mjs',
5+
'.madrun.cjs',
6+
].map(joinPartial(cwd));
7+
8+
for (const name of madrunNames) {
9+
const [error] = await tryToCatch(access, name);
10+
11+
if (!error)
12+
return name;
13+
}
14+
15+
return '';
16+
}

0 commit comments

Comments
 (0)