diff --git a/lib/utils.js b/lib/utils.js index 6c3896d..930466a 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -20,30 +20,38 @@ const packages = getPackages(process.cwd()).map( }), ); +const isImportExpression = expression => + expression.type === 'CallExpression' && + expression.arguments.length > 0 && + expression.arguments[0].type === 'Literal' && + (expression.callee.type === 'Import' || + (expression.callee.type === 'Identifier' && + expression.callee.name === 'require')); + +const resolveImport = (context, node, { value, range }) => { + const path = resolve(dirname(context.getFilename()), value); + const [start, end] = range; + return { node, value, path, start, end }; +}; + const getImport = (context, callback) => ({ ImportDeclaration: node => { if (node.source.type === 'Literal') { - const { value, range } = node.source; - const path = resolve(dirname(context.getFilename()), value); - const [start, end] = range; - callback({ node, value, path, start, end }); + callback(resolveImport(context, node, node.source)); } }, ExpressionStatement: node => { - if ( - node.expression.type === 'CallExpression' && - node.expression.arguments.length > 0 && - node.expression.arguments[0].type === 'Literal' && - (node.expression.callee.type === 'Import' || - (node.expression.callee.type === 'Identifier' && - node.expression.callee.name === 'require')) - ) { - const { value, range } = node.expression.arguments[0]; - const path = resolve(dirname(context.getFilename()), value); - const [start, end] = range; - callback({ node, value, path, start, end }); + if (isImportExpression(node.expression)) { + callback(resolveImport(context, node, node.expression.arguments[0])); } }, + VariableDeclaration: node => { + node.declarations.forEach(({ init }) => { + if (isImportExpression(init)) { + callback(resolveImport(context, node, init.arguments[0])); + } + }); + }, }); module.exports = { isSubPath, packages, getImport }; diff --git a/tests/rules/no-cross-imports.js b/tests/rules/no-cross-imports.js index 5d6982e..70de1f1 100644 --- a/tests/rules/no-cross-imports.js +++ b/tests/rules/no-cross-imports.js @@ -50,6 +50,15 @@ ruleTester.run('no-cross-imports', rule, { }, ], }, + { + code: "const test = import('@test/workspace');", + filename: '/some/path.js', + errors: [ + { + message: 'Import from package "@test/workspace" is not allowed', + }, + ], + }, { code: "require('@test/workspace');", filename: '/some/path.js', @@ -59,6 +68,15 @@ ruleTester.run('no-cross-imports', rule, { }, ], }, + { + code: "const test = require('@test/workspace');", + filename: '/some/path.js', + errors: [ + { + message: 'Import from package "@test/workspace" is not allowed', + }, + ], + }, { code: "import workspace from '@test/workspace';", filename: '/some/path.js',