vite-plugin-commonjs
A pure JavaScript implementation of CommonJs
English | 简体中文
✅ alias
✅ bare module(node_modules)
✅ dynamic-require similar to 👉 Webpack require('./foo/' + bar)
Usage
import commonjs from 'vite-plugin-commonjs'
export default {
plugins: [
commonjs(),
]
}
API (Define)
export interface CommonjsOptions {
filter?: (id: string) => boolean | undefined
dynamic?: {
loose?: boolean
onFiles?: (files: string[], id: string) => typeof files | undefined
}
advanced?: {
importRules?: ImportInteropType | ((id: string) => ImportInteropType | string)
}
}
node_modules
commonjs({
filter(id) {
if (id.includes('node_modules/xxx')) {
return true
}
}
})
Cases
vite-plugin-commonjs/test
✅ require statement
const foo = require('foo').default
import foo from 'foo'
const foo = require('foo')
import * as foo from 'foo'
const foo = require('foo').bar
import * as __CJS_import__0__ from 'foo'; const { bar: foo } = __CJS_import__0__
const foo = [{ bar: require('foo').bar }]
↓
import * as __CJS_import__0__ from 'foo'; const foo = [{ bar: __CJS_import__0__.bar }]
✅ exports statement
module.exports = fn() { }
const __CJS__export_default__ = module.exports = fn() { }
export { __CJS__export_default__ as default }
exports.foo = 'foo'
const __CJS__export_foo__ = (module.exports == null ? {} : module.exports).foo
export { __CJS__export_foo__ as foo }
✅ dynamic-require statement
We assume that the project structure is as follows
├─┬ src
│ ├─┬ views
│ │ ├─┬ foo
│ │ │ └── index.js
│ │ └── bar.js
│ └── router.js
└── vite.config.js
function load(name: string) {
return require(`./views/${name}`)
}
import * as __dynamic_require2import__0__0 from './views/foo/index.js'
import * as __dynamic_require2import__0__1 from './views/bar.js'
function load(name: string) {
return __matchRequireRuntime0__(`./views/${name}`)
}
function __matchRequireRuntime0__(path) {
switch(path) {
case './views/foo':
case './views/foo/index':
case './views/foo/index.js':
return __dynamic_require2import__0__0;
case './views/bar':
case './views/bar.js':
return __dynamic_require2import__0__1;
default: throw new Error("Cann't found module: " + path);
}
}