New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More →
Socket
Sign inDemoInstall
Socket

vite-plugin-esmodule

Package Overview
Dependencies
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vite-plugin-esmodule - npm Package Compare versions

Comparing version 1.0.1 to 1.1.0

README.zh-CN.md

20

index.d.ts

@@ -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[];
}

@@ -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)
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡ī¸ by Socket Inc