vite-plugin-esmodule
Advanced tools
Comparing version 1.0.1 to 1.1.0
@@ -1,2 +0,3 @@ | ||
import { Plugin } from 'vite'; | ||
import type { Plugin, UserConfig } from 'vite'; | ||
import type { Configuration } from 'webpack'; | ||
@@ -6,10 +7,17 @@ export default esmodule; | ||
// TODO: support options | ||
export interface EsmoduleOptions { | ||
dir?: string; | ||
config?: Plugin['config']; | ||
export interface WebpackOptions { | ||
webpack?: true | ((config: Configuration) => Configuration | void | Promise<Configuration | void>); | ||
vite: never; | ||
} | ||
export interface ViteOptions { | ||
vite?: true | ((config: UserConfig) => UserConfig | void | Promise<UserConfig | void>); | ||
webpack: never; | ||
} | ||
export interface Esmodule { | ||
(modules: string[]): Plugin[]; | ||
( | ||
modules: (string | { [module: string]: string })[], | ||
options?: WebpackOptions | ViteOptions, | ||
): Plugin[]; | ||
} |
164
index.js
@@ -0,8 +1,9 @@ | ||
const fs = require('fs'); | ||
const path = require('path'); | ||
const { builtinModules } = require('module'); | ||
const { build } = require('vite'); | ||
const resolve = require('vite-plugin-resolve'); | ||
const vite = require('vite'); | ||
const webpack = require('webpack'); | ||
const optimizer = require('vite-plugin-optimizer'); | ||
const { externalBuiltin } = require('./utils'); | ||
// TODO: Modify by options.dir | ||
let name = 'vite-plugin-esmodule'; | ||
const name = 'vite-plugin-esmodule'; | ||
@@ -12,10 +13,11 @@ /** | ||
*/ | ||
module.exports = function esmodule(modules = []) { | ||
const plugin = resolve({ | ||
...modules.reduce((memo, mod) => Object.assign(memo, { | ||
async [mod](args) { | ||
await buildEsmodule(args.dir, mod); | ||
}, | ||
module.exports = function esmodule(modules, options = {}) { | ||
const plugin = optimizer( | ||
modules.reduce((memo, mod, idx) => Object.assign(memo, { | ||
[mod]: args => idx === modules.length - 1 | ||
? buildESModules(args, modules, options) // One time build | ||
: null, | ||
}), {}), | ||
}, { dir: `.${name}` }); | ||
{ dir: `.${name}` }, | ||
); | ||
@@ -33,2 +35,3 @@ plugin.name = name; | ||
const module = modules.find(mod => mod === source); | ||
// Tell vite not to process this module | ||
if (module) module; | ||
@@ -42,45 +45,102 @@ }, | ||
/** | ||
* @type {() => import('vite').Plugin} | ||
* Build CommonJs module here, | ||
* and output the file to the alias pointing path of vite-plugin-optimizer | ||
* | ||
* @type {(args: import('vite-plugin-optimizer').OptimizerArgs, ...args: Parameters<import('.').Esmodule>) => Promise<void>} | ||
*/ | ||
function externalBuiltin() { | ||
return { | ||
name: 'vite-plugin-external-builtin', | ||
apply: 'build', | ||
enforce: 'pre', | ||
resolveId(source) { | ||
if (source.startsWith('node:')) { | ||
source = source.replace('node:', ''); | ||
} | ||
if (builtinModules.includes(source)) { | ||
return { | ||
external: true, | ||
id: source, | ||
}; | ||
} | ||
}, | ||
}; | ||
} | ||
async function buildESModules(args, modules, options) { | ||
const node_modules = args.dir.replace(`.${name}`, ''); | ||
const entries = modules.reduce((memo, mod) => { | ||
const [key, val] = typeof mod === 'object' ? Object.entries(mod)[0] : [mod, mod]; | ||
return Object.assign(memo, { [key]: path.resolve(node_modules, val) }); | ||
}, {}); | ||
/** | ||
* @type {(dir: string, moduleId: string) => Promise<void>} | ||
*/ | ||
async function buildEsmodule(dir, moduleId) { | ||
await build({ | ||
// đ§ Avoid recursive build caused by load config file | ||
configFile: false, | ||
plugins: [ | ||
externalBuiltin(), | ||
], | ||
build: { | ||
minify: false, | ||
sourcemap: true, | ||
emptyOutDir: false, | ||
lib: { | ||
entry: path.join(dir.replace(`.${name}`, ''), moduleId), | ||
formats: ['cjs'], | ||
fileName: () => '[name].js', | ||
if (options.webpack) { | ||
/** | ||
* @type {import('webpack').Configuration} | ||
*/ | ||
let config = { | ||
mode: 'none', | ||
target: 'node10', | ||
entry: entries, | ||
output: { | ||
library: { | ||
type: 'commonjs2', | ||
}, | ||
path: args.dir, | ||
filename: '[name].js', | ||
}, | ||
outDir: path.join(dir, moduleId), | ||
}, | ||
}); | ||
}; | ||
if (typeof options.webpack === 'function') { | ||
config = options.webpack(config) || config; | ||
} | ||
await new Promise(resolve => { | ||
fs.rmSync(args.dir, { recursive: true, force: true }); | ||
webpack.webpack(config).run((error, stats) => { | ||
resolve(null); | ||
if (error) { | ||
console.log(error); | ||
process.exit(1); | ||
} | ||
if (stats.hasErrors()) { | ||
stats.toJson().errors.forEach(msg => { | ||
console.log(msg.message, '\n'); | ||
console.log(msg.stack, '\n'); | ||
}); | ||
process.exit(1); | ||
} | ||
console.log(`[${name}] build with webpack success.`); | ||
}); | ||
}); | ||
} else { | ||
Object.entries(entries).forEach(async ([moduleId, filepath]) => { | ||
await vite.build({ | ||
// đ§ Avoid recursive build caused by load config file | ||
configFile: false, | ||
plugins: [ | ||
externalBuiltin(), | ||
], | ||
build: { | ||
minify: false, | ||
emptyOutDir: false, | ||
lib: { | ||
entry: filepath, | ||
formats: ['cjs'], | ||
fileName: () => '[name].js', | ||
}, | ||
outDir: path.join(args.dir, moduleId), | ||
}, | ||
}); | ||
}); | ||
/** | ||
* TODO: Building multiple modules in parallel | ||
// Built using vite by default | ||
await vite.build({ | ||
// đ§ Avoid recursive build caused by load config file | ||
configFile: false, | ||
plugins: [ | ||
externalBuiltin(), | ||
], | ||
build: { | ||
minify: false, | ||
emptyOutDir: false, | ||
outDir: args.dir, | ||
rollupOptions: { | ||
input: entries, | ||
output: { | ||
format: 'cjs', | ||
entryFileNames: '[name]/index.js', | ||
chunkFileNames: '[name].js', | ||
assetFileNames: '[name].[ext]', | ||
}, | ||
}, | ||
}, | ||
}); | ||
*/ | ||
} | ||
} |
{ | ||
"name": "vite-plugin-esmodule", | ||
"version": "1.0.1", | ||
"version": "1.1.0", | ||
"description": "Build ES module to CommonJs module for Node.js", | ||
@@ -29,7 +29,8 @@ "main": "index.js", | ||
"dependencies": { | ||
"vite-plugin-resolve": "^1.8.0" | ||
"vite-plugin-optimizer": "^1.1.4", | ||
"webpack": "^5.x.x" | ||
}, | ||
"devDependencies": { | ||
"vite": "^2.6.13" | ||
"vite": "^2.x" | ||
} | ||
} |
@@ -0,2 +1,7 @@ | ||
# vite-plugin-esmodule | ||
[![npm package](https://nodei.co/npm/vite-plugin-esmodule.png?downloads=true&downloadRank=true&stars=true)](https://www.npmjs.com/package/vite-plugin-esmodule) | ||
<br/> | ||
[![NPM version](https://img.shields.io/npm/v/vite-plugin-esmodule.svg?style=flat)](https://npmjs.org/package/vite-plugin-esmodule) | ||
[![NPM Downloads](https://img.shields.io/npm/dm/vite-plugin-esmodule.svg?style=flat)](https://npmjs.org/package/vite-plugin-esmodule) | ||
@@ -7,14 +12,17 @@ Build ES module to CommonJs module for Node.js | ||
[![NPM version](https://img.shields.io/npm/v/vite-plugin-esmodule.svg?style=flat)](https://npmjs.org/package/vite-plugin-esmodule) | ||
[![NPM Downloads](https://img.shields.io/npm/dm/vite-plugin-esmodule.svg?style=flat)](https://npmjs.org/package/vite-plugin-esmodule) | ||
## Why | ||
When ES module such as [execa](https://www.npmjs.com/package/execa), [node-fetch](https://www.npmjs.com/package/node-fetch) used in the Node.js project, we should compile them into CommonJs modules to ensure that they can work | ||
When ES module such as [execa](https://www.npmjs.com/package/execa), [node-fetch](https://www.npmjs.com/package/node-fetch), [file-type](https://www.npmjs.com/package/file-type) used in the Node.js project, we should compile them into CommonJs modules to ensure that they can work | ||
**đĸ The plugin only work in the `vite build` phase** | ||
## đ§ Warning | ||
The plugin only work in the `vite build` phase | ||
The Plugin built NPM Packages use Vite by default, of course you can specify use Webpack by `options.webpack` | ||
If some NPM Packges have problems after being built with vite, please choose to build with `options.webpack` | ||
## Usage | ||
Take execa and node fetch as examples | ||
Take execa, node-fetch and file-type as examples | ||
@@ -31,2 +39,4 @@ - vite.config.js | ||
'node-fetch', | ||
// file-type have exports condition in package.json | ||
{ 'file-type': 'file-type/index.js' }, | ||
]), | ||
@@ -47,24 +57,32 @@ ], | ||
- node-fetch.js | ||
See the test [cases](https://github.com/caoxiemeihao/vite-plugins/tree/main/playground/vite-plugin-esmodule) | ||
```js | ||
import fetch from 'node-fetch'; | ||
## API | ||
const response = await fetch('https://github.com/'); | ||
const body = await response.text(); | ||
#### esmodule(modules[,options]) | ||
console.log(body); | ||
modules: ES module name list | ||
```ts | ||
modules: (string | { [module: string]: string })[] | ||
``` | ||
See the test [cases](https://github.com/caoxiemeihao/vite-plugins/tree/main/playground/vite-plugin-esmodule) | ||
options: | ||
## API | ||
```ts | ||
options?: WebpackOptions | ViteOptions | ||
#### esmodule(modules: string[]) | ||
export interface WebpackOptions { | ||
webpack?: true | ((config: Configuration) => Configuration | void | Promise<Configuration | void>); | ||
vite: never; | ||
} | ||
modules: ES module name list | ||
export interface ViteOptions { | ||
vite?: true | ((config: UserConfig) => UserConfig | void | Promise<UserConfig | void>); | ||
webpack: never; | ||
} | ||
``` | ||
## How to work | ||
The plugin will use the `build` API of Vite to build ES module into the `node_modules/.vite-plugin-esmodule` directory | ||
Then point to the built path by modifying `resolve.alias` | ||
This plugin just wraps [vite-plugin-optimizer](https://github.com/caoxiemeihao/vite-plugins/tree/main/packages/optimizer) |
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
8955
6
172
86
2
2
+ Addedvite-plugin-optimizer@^1.1.4
+ Addedwebpack@^5.x.x
+ Added@jridgewell/gen-mapping@0.3.8(transitive)
+ Added@jridgewell/resolve-uri@3.1.2(transitive)
+ Added@jridgewell/set-array@1.2.1(transitive)
+ Added@jridgewell/source-map@0.3.6(transitive)
+ Added@jridgewell/sourcemap-codec@1.5.0(transitive)
+ Added@jridgewell/trace-mapping@0.3.25(transitive)
+ Added@types/eslint@9.6.1(transitive)
+ Added@types/eslint-scope@3.7.7(transitive)
+ Added@types/estree@1.0.6(transitive)
+ Added@types/json-schema@7.0.15(transitive)
+ Added@types/node@22.13.1(transitive)
+ Added@webassemblyjs/ast@1.14.1(transitive)
+ Added@webassemblyjs/floating-point-hex-parser@1.13.2(transitive)
+ Added@webassemblyjs/helper-api-error@1.13.2(transitive)
+ Added@webassemblyjs/helper-buffer@1.14.1(transitive)
+ Added@webassemblyjs/helper-numbers@1.13.2(transitive)
+ Added@webassemblyjs/helper-wasm-bytecode@1.13.2(transitive)
+ Added@webassemblyjs/helper-wasm-section@1.14.1(transitive)
+ Added@webassemblyjs/ieee754@1.13.2(transitive)
+ Added@webassemblyjs/leb128@1.13.2(transitive)
+ Added@webassemblyjs/utf8@1.13.2(transitive)
+ Added@webassemblyjs/wasm-edit@1.14.1(transitive)
+ Added@webassemblyjs/wasm-gen@1.14.1(transitive)
+ Added@webassemblyjs/wasm-opt@1.14.1(transitive)
+ Added@webassemblyjs/wasm-parser@1.14.1(transitive)
+ Added@webassemblyjs/wast-printer@1.14.1(transitive)
+ Added@xtuc/ieee754@1.2.0(transitive)
+ Added@xtuc/long@4.2.2(transitive)
+ Addedacorn@8.14.0(transitive)
+ Addedajv@6.12.68.17.1(transitive)
+ Addedajv-formats@2.1.1(transitive)
+ Addedajv-keywords@3.5.25.1.0(transitive)
+ Addedbrowserslist@4.24.4(transitive)
+ Addedbuffer-from@1.1.2(transitive)
+ Addedcaniuse-lite@1.0.30001696(transitive)
+ Addedchrome-trace-event@1.0.4(transitive)
+ Addedcommander@2.20.3(transitive)
+ Addedelectron-to-chromium@1.5.91(transitive)
+ Addedenhanced-resolve@5.18.0(transitive)
+ Addedes-module-lexer@1.6.0(transitive)
+ Addedescalade@3.2.0(transitive)
+ Addedeslint-scope@5.1.1(transitive)
+ Addedesrecurse@4.3.0(transitive)
+ Addedestraverse@4.3.05.3.0(transitive)
+ Addedevents@3.3.0(transitive)
+ Addedfast-deep-equal@3.1.3(transitive)
+ Addedfast-json-stable-stringify@2.1.0(transitive)
+ Addedfast-uri@3.0.6(transitive)
+ Addedglob-to-regexp@0.4.1(transitive)
+ Addedgraceful-fs@4.2.11(transitive)
+ Addedhas-flag@4.0.0(transitive)
+ Addedjest-worker@27.5.1(transitive)
+ Addedjson-parse-even-better-errors@2.3.1(transitive)
+ Addedjson-schema-traverse@0.4.11.0.0(transitive)
+ Addedloader-runner@4.3.0(transitive)
+ Addedmerge-stream@2.0.0(transitive)
+ Addedmime-db@1.52.0(transitive)
+ Addedmime-types@2.1.35(transitive)
+ Addedneo-async@2.6.2(transitive)
+ Addednode-releases@2.0.19(transitive)
+ Addedpicocolors@1.1.1(transitive)
+ Addedpunycode@2.3.1(transitive)
+ Addedrandombytes@2.1.0(transitive)
+ Addedrequire-from-string@2.0.2(transitive)
+ Addedsafe-buffer@5.2.1(transitive)
+ Addedschema-utils@3.3.04.3.0(transitive)
+ Addedserialize-javascript@6.0.2(transitive)
+ Addedsource-map@0.6.1(transitive)
+ Addedsource-map-support@0.5.21(transitive)
+ Addedsupports-color@8.1.1(transitive)
+ Addedtapable@2.2.1(transitive)
+ Addedterser@5.37.0(transitive)
+ Addedterser-webpack-plugin@5.3.11(transitive)
+ Addedundici-types@6.20.0(transitive)
+ Addedupdate-browserslist-db@1.1.2(transitive)
+ Addeduri-js@4.4.1(transitive)
+ Addedvite-plugin-optimizer@1.4.3(transitive)
+ Addedwatchpack@2.4.2(transitive)
+ Addedwebpack@5.97.1(transitive)
+ Addedwebpack-sources@3.2.3(transitive)
- Removedvite-plugin-resolve@^1.8.0
- Removedvite-plugin-resolve@1.8.0(transitive)