Skip to content

Commit

Permalink
feature(@putout/plugin-convert-commonjs-to-esm) commons: add support …
Browse files Browse the repository at this point in the history
…of top-level-require
  • Loading branch information
coderaiser committed Aug 25, 2021
1 parent 359c317 commit 2c39229
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const a = require('./package.json');
17 changes: 16 additions & 1 deletion packages/plugin-convert-commonjs-to-esm/lib/commons/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@
const {
template,
operator,
types,
} = require('putout');

const {getPathAfterImports} = operator;
const {isProgram} = types;

const importSimport = template.ast(`import {createCommons} from 'simport'`);
const initCommons = template.ast(`const {__filename, __dirname, require} = createCommons(import.meta.url)`);
Expand All @@ -29,11 +32,23 @@ module.exports.include = () => [
'require',
];

module.exports.filter = ({scope}) => {
module.exports.filter = (path) => {
const {scope} = path;

const isDirname = scope.hasBinding('__dirname');
const isFilename = scope.hasBinding('__filename');
const isRequire = scope.hasBinding('require');

if (isTopLevelRequire(path))
return false;

return !isDirname && !isFilename && !isRequire;
};

function isTopLevelRequire(path) {
if (path.node.name !== 'require')
return false;

return isProgram(path.scope.block);
}

Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ test('plugin-convert-commonjs-to-esm: commons: transform: require', (t) => {
t.end();
});

test('plugin-convert-commonjs-to-esm: commons: no transform: top-level-require', (t) => {
t.noTransform('top-level-require');
t.end();
});

test('plugin-convert-commonjs-to-esm: commons: no transform: declared require', (t) => {
t.noTransform('declared-require');
t.end();
Expand Down

0 comments on commit 2c39229

Please sign in to comment.