Path: blob/main/src/rules/no-import-module-exports.js
829 views
import minimatch from 'minimatch';1import path from 'path';2import pkgUp from 'eslint-module-utils/pkgUp';34function getEntryPoint(context) {5const pkgPath = pkgUp({ cwd: context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename() });6try {7return require.resolve(path.dirname(pkgPath));8} catch (error) {9// Assume the package has no entrypoint (e.g. CLI packages)10// in which case require.resolve would throw.11return null;12}13}1415function findScope(context, identifier) {16const { scopeManager } = context.getSourceCode();1718return scopeManager && scopeManager.scopes.slice().reverse().find((scope) => scope.variables.some(variable => variable.identifiers.some((node) => node.name === identifier)));19}2021module.exports = {22meta: {23type: 'problem',24docs: {25description: 'Disallow import statements with module.exports',26category: 'Best Practices',27recommended: true,28},29fixable: 'code',30schema: [31{32'type': 'object',33'properties': {34'exceptions': { 'type': 'array' },35},36'additionalProperties': false,37},38],39},40create(context) {41const importDeclarations = [];42const entryPoint = getEntryPoint(context);43const options = context.options[0] || {};44let alreadyReported = false;4546function report(node) {47const fileName = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename();48const isEntryPoint = entryPoint === fileName;49const isIdentifier = node.object.type === 'Identifier';50const hasKeywords = (/^(module|exports)$/).test(node.object.name);51const objectScope = hasKeywords && findScope(context, node.object.name);52const hasCJSExportReference = hasKeywords && (!objectScope || objectScope.type === 'module');53const isException = !!options.exceptions && options.exceptions.some(glob => minimatch(fileName, glob));5455if (isIdentifier && hasCJSExportReference && !isEntryPoint && !isException) {56importDeclarations.forEach(importDeclaration => {57context.report({58node: importDeclaration,59message: `Cannot use import declarations in modules that export using ` +60`CommonJS (module.exports = 'foo' or exports.bar = 'hi')`,61});62});63alreadyReported = true;64}65}6667return {68ImportDeclaration(node) {69importDeclarations.push(node);70},71MemberExpression(node) {72if (!alreadyReported) {73report(node);74}75},76};77},78};798081