Migrate express.static.mime
In Express 5, mime is no longer an exported property of express.static. The
mime-types package should be used to
work with MIME type values instead.
This codemod rewrites every express.static.mime reference to use a mime-types
binding and adds the corresponding import/require to the file:
- Replaces
express.static.mimewith amime-typeslocal binding (default namemime). - Adds the import once per file, matching how
expressis imported
(import mime from 'mime-types'for ESM,const mime = require('mime-types')for CommonJS). - Reuses an existing
mime-typesimport when the file already has one, and falls
back to a non-colliding name (mimeTypes) whenmimeis already taken.
The object Express 4 exposed as express.static.mime was a mime@1.x
instance, whose API is not identical to mime-types. The codemod rewrites
each member accordingly:
express.static.mime (mime@1.x) | mime-types | Handled by |
|---|---|---|
.lookup(path) | .lookup(path) | rename of the binding |
.extension(type) | .extension(type) | rename of the binding |
.types / .extensions | .types / .extensions | rename of the binding |
.charsets.lookup(type) | .charset(type) | method rewrite |
.define(map) | no equivalent | flagged with a TODO comment |
.load(path) | no equivalent | flagged with a TODO comment |
.default_type | no equivalent | flagged with a TODO comment |
Example
diff
Renamed method
diff
Methods without a mime-types equivalent
define, load, and default_type cannot be migrated automatically, so the
codemod points them at the new binding and flags them for manual review:
diff
CommonJS
diff
package.json
For projects that depend on express, the codemod also adds mime-types to the
same dependency section, so the newly referenced package is declared:
diff
An existing mime-types entry is left untouched, and package.json files without
express are not modified.
Notes
- Behavior differs slightly even for the shared methods:
mime-typesreturns
falsefor unknown input, whereasmime@1.xlookup()fell back to
default_type(application/octet-stream). Review code that relied on that
fallback. - Members flagged with a
TODOcomment (define,load,default_type) have no
mime-typesequivalent and must be migrated by hand. - Run
npm installafter the migration so the addedmime-typesdependency is installed.