unicorn/import-style

Enforce how each module is imported: named, default, namespace, or for side effects

You can import most modules in several ways. If one file writes path.join() and the next writes join(), the same function has two names in your project, and a search finds only half of its uses. This rule lets you choose the import styles for a module and reports the others.

There are four styles:

StyleLooks like
namedimport { join } from "node:path"
defaultimport path from "node:path"
namespaceimport * as path from "node:path"
unassignedimport "node:path"

Without any options, path, node:path and chalk need a default import, and util and node:util need named imports. No other module is checked.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/import-style" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[lint.rules]
"unicorn/import-style" = ["error", {
  styles = {},
  extendDefaultStyles = true,
  checkImport = true,
  checkDynamicImport = true,
  checkRequire = true,
  checkExportFrom = false,
}]

Examples#

example.js2 problems
import { join } from "node:path";
import util from "node:util";
example.jsNo problems
import path from "node:path";
import { promisify } from "node:util";

require() and await import() are checked too. const path = require("path") is accepted wherever a default import is. const path = await import("path") is a namespace import.

example.js2 problems
const { join } = require("path");
const chalk = await import("chalk");
example.jsNo problems
const path = require("path");
const { default: chalk } = await import("chalk");
const { promisify } = await import("node:util");

Options#

OptionDefaultWhat it does
styles{}For each module name, the styles you allow (true) or forbid (false). false instead of an object turns off the check for that module.
extendDefaultStylestrueKeep the default styles for path, util and chalk, and merge styles into them.
checkImporttrueCheck import declarations.
checkDynamicImporttrueCheck import().
checkRequiretrueCheck require().
checkExportFromfalseAlso check export ... from.
bunfig.toml
[lint.rules]
"unicorn/import-style" = ["error", { styles = { react = { named = true } } }]
example.jswith { "styles": { "react": { "named": true } } }1 problem
import React from "react";
example.jswith { "styles": { "react": { "named": true } } }No problems
import { useState } from "react";

Anything you set for path, util or chalk is added to the defaults. This allows a default import of node:util and still allows named imports. Add "named": false to forbid those.

example.jswith { "styles": { "node:util": { "default": true } } }No problems
import util from "node:util";
import { promisify } from "node:util";

false turns a module off:

example.jswith { "styles": { "node:path": false } }No problems
import { join } from "node:path";

With checkExportFrom:

example.jswith { "checkExportFrom": true }1 problem
export { join } from "node:path";