An ESLint plugin to enforce optimal JavaScript module design.
To install eslint-plugin-optimal-modules
with npm, run:
npm install eslint-plugin-optimal-modules --save-dev
To use the recommended config, add the following ESLint “flat” config in eslint.config.mjs
:
// @ts-check
import eslintPluginOptimalModules from "eslint-plugin-optimal-modules";
/**
* ESLint config.
* @satisfies {Array<import("eslint").Linter.Config>}
*/
const eslintConfig = [eslintPluginOptimalModules.configs.recommended];
export default eslintConfig;
Alternatively, manually configure the plugin and the desired rules:
// @ts-check
import eslintPluginOptimalModules from "eslint-plugin-optimal-modules";
/**
* ESLint config.
* @satisfies {Array<import("eslint").Linter.Config>}
*/
const eslintConfig = [
{
plugins: {
"optimal-modules": eslintPluginOptimalModules,
},
rules: {
"optimal-modules/no-named-exports": "error",
},
},
];
export default eslintConfig;
To allow named exports in Storybook story modules that have a Component Story Format (CSF):
// @ts-check
import eslintPluginOptimalModules from "eslint-plugin-optimal-modules";
/**
* ESLint config.
* @satisfies {Array<import("eslint").Linter.Config>}
*/
const eslintConfig = [
eslintPluginOptimalModules.configs.recommended,
{
files: ["**/*.stories.{mjs,cjs,js,mts,cts,ts,tsx}"],
rules: {
"optimal-modules/no-named-exports": "off",
},
},
];
export default eslintConfig;
Prohibits using named exports for optimal module design.
Valid examples:
// No exports.
const a = true;
// Default export.
export default true;
// Default export.
const a = true;
export { a as default };
// TypeScript type default export.
type A = boolean;
export type { A as default };
Invalid examples:
// Named export.
export const a = true;
// Named export.
const a = true;
export { a };
// TypeScript type named export.
export type A = boolean;
To fix the above errors, move the thing being exported to its own module as a default export.
Enabled rules:
no-named-exports
(error).
Supported runtime environments:
- Node.js versions
^18.18.0 || ^20.9.0 || >=21.1.0
.
Projects must configure TypeScript to use types from the CommonJS modules that have a // @ts-check
comment:
compilerOptions.allowJs
should betrue
.compilerOptions.maxNodeModuleJsDepth
should be reasonably large, e.g.10
.compilerOptions.module
should be"node16"
or"nodenext"
.
These CommonJS modules are exported via the package.json
field exports
: