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

vite-express

Package Overview
Dependencies
Maintainers
1
Versions
40
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

vite-express - npm Package Compare versions

Comparing version 0.8.0 to 0.9.0

11

dist/main.d.ts

@@ -8,6 +8,15 @@ /// <reference types="qs" />

import https from "https";
type ViteConfig = {
root?: string;
base?: string;
build?: {
outDir: string;
};
};
declare const Config: {
mode: "production" | "development";
inlineViteConfig: ViteConfig | undefined;
transformer: ((html: string, req: express.Request) => string) | undefined;
};
type ConfigurationOptions = Partial<Omit<typeof Config, "viteServerSecure">>;
type ConfigurationOptions = Partial<typeof Config>;
declare function config(config: ConfigurationOptions): void;

@@ -14,0 +23,0 @@ declare function bind(app: core.Express, server: http.Server | https.Server, callback?: () => void): Promise<void>;

67

dist/main.js

@@ -7,3 +7,2 @@ 'use strict';

var pc = require('picocolors');
var Vite = require('vite');

@@ -38,2 +37,4 @@ /******************************************************************************

mode: (NODE_ENV === "production" ? "production" : "development"),
inlineViteConfig: undefined,
transformer: undefined,
};

@@ -47,11 +48,34 @@ function info(msg) {

}
function getTransformedHTML(html, req) {
return Config.transformer ? Config.transformer(html, req) : html;
}
function isRunningViteless() {
return Config.inlineViteConfig !== undefined;
}
function resolveConfig() {
return __awaiter(this, void 0, void 0, function* () {
if (!Config.inlineViteConfig) {
const { resolveConfig } = yield import('vite');
return resolveConfig({}, "build");
}
const { root = process.cwd(), base = "/", build = { outDir: "dist" }, } = Config.inlineViteConfig;
return { root, base, build };
});
}
function getDistPath() {
return __awaiter(this, void 0, void 0, function* () {
const config = yield resolveConfig();
return path.resolve(config.root, config.build.outDir);
});
}
function serveStatic() {
return __awaiter(this, void 0, void 0, function* () {
const config = yield Vite.resolveConfig({}, "build");
const distPath = path.resolve(config.root, config.build.outDir);
const distPath = yield getDistPath();
if (!fs.existsSync(distPath)) {
info(`${pc.yellow(`Static files at ${pc.gray(distPath)} not found!`)}`);
yield build();
info(`${pc.red(`Static files at ${pc.gray(distPath)} not found!`)}`);
info(`${pc.yellow(`Did you forget to run ${pc.bold(pc.green("vite build"))} command?`)}`);
}
info(`${pc.green(`Serving static files from ${pc.gray(distPath)}`)}`);
else {
info(`${pc.green(`Serving static files from ${pc.gray(distPath)}`)}`);
}
return express.static(distPath, { index: false });

@@ -63,3 +87,5 @@ });

return __awaiter(this, void 0, void 0, function* () {
app.use(middleware);
const config = yield resolveConfig();
const base = config.base || "/";
app.use(base, middleware);
const stubMiddlewareLayer = app._router.stack.find((layer) => layer.handle === stubMiddleware);

@@ -76,3 +102,3 @@ if (stubMiddlewareLayer !== undefined) {

return __awaiter(this, void 0, void 0, function* () {
const config = yield Vite.resolveConfig({}, "build");
const config = yield resolveConfig();
const template = fs.readFileSync(path.resolve(config.root, "index.html"), "utf8");

@@ -82,4 +108,6 @@ app.get("/*", (req, res, next) => __awaiter(this, void 0, void 0, function* () {

next();
else
res.send(yield server.transformIndexHtml(req.originalUrl, template));
else {
const html = yield server.transformIndexHtml(req.originalUrl, template);
res.send(getTransformedHTML(html, req));
}
}));

@@ -90,6 +118,6 @@ });

return __awaiter(this, void 0, void 0, function* () {
const config = yield Vite.resolveConfig({}, "build");
const distPath = path.resolve(config.root, config.build.outDir);
app.use("*", (_, res) => {
res.sendFile(path.resolve(distPath, "index.html"));
const distPath = yield getDistPath();
const html = fs.readFileSync(path.resolve(distPath, "index.html"), "utf-8");
app.use("*", (req, res) => {
res.send(getTransformedHTML(html, req));
});

@@ -100,3 +128,4 @@ });

return __awaiter(this, void 0, void 0, function* () {
const vite = yield Vite.createServer({
const { createServer } = yield import('vite');
const vite = yield createServer({
clearScreen: false,

@@ -113,2 +142,4 @@ appType: "custom",

Config.mode = config.mode;
Config.inlineViteConfig = config.inlineViteConfig;
Config.transformer = config.transformer;
}

@@ -124,2 +155,5 @@ function bind(app, server, callback) {

else {
if (isRunningViteless()) {
info(`Custom inline config defined, running in ${pc.yellow("viteless")} mode`);
}
yield injectStaticMiddleware(app, yield serveStatic());

@@ -137,4 +171,5 @@ yield injectIndexMiddleware(app);

return __awaiter(this, void 0, void 0, function* () {
const { build } = yield import('vite');
info("Build starting...");
yield Vite.build();
yield build();
info("Build completed!");

@@ -141,0 +176,0 @@ });

{
"name": "vite-express",
"version": "0.8.0",
"version": "0.9.0",
"main": "dist/main.js",

@@ -23,3 +23,2 @@ "types": "dist/main.d.ts",

"dependencies": {
"node-fetch": "^2.0.0",
"picocolors": "^1.0.0"

@@ -26,0 +25,0 @@ },

@@ -12,2 +12,3 @@ # ⚡ Vite + Express

- [🚚 Shipping to production](#-shipping-to-production)
- [🤖 Transforming HTML](#-transforming-html)
- [🤔 How does it work?](#-how-does-it-work)

@@ -151,2 +152,93 @@ - [📝 Documentation](#-documentation)

### ⚡ Viteless mode
`vite-express` uses Vite even in production to resolve [`vite.config.js`][vite-config] correctly. If you want to be able to run your production app without Vite and all development dependencies, you need to specify custom inline config using `ViteExpress.config({ inlineViteConfig: ... })`.
Valid configuration values used by `vite-express` are [`root`][root], [`base`][base] and [`outDir`][outDir].
- When `inlineViteConfig` is set to `undefined` (by default) Vite is used in production to resolve config file
- To use viteless mode with the defaults you can set `inlineViteConfig` as `{}`
```javascript
import express from "express";
import ViteExpress from "vite-express";
ViteExpress.config({ inlineViteConfig: {} })
ViteExpress.listen(express(), 3000);
```
- You can also specify any combination of valid parameters
```javascript
import express from "express";
import ViteExpress from "vite-express";
ViteExpress.config({
inlineViteConfig: {
base: "/admin",
build: { outDir: "out" }
}
});
ViteExpress.listen(express(), 3000);
```
Be aware that in viteless mode you have two separate sources of truth - `vite.config.js` and your inline configuration, so you need to manually keep them in sync.
Most of the time you are okay with using Vite in production as it's easier, this approach is only recommended if you want to reduce production dependencies.
## 🤖 Transforming HTML
You can specify transformer function that takes two arguments - HTML as a string and [`Request`][express-request] object - and returns HTML as a string with any string related transformation applied. It can be used to inject your custom metadata on the server-side.
This transformer function is invoked right before sending the HTML to the client in the index-serving middleware that `vite-express` injects at the end of the middleware stack.
Imagine a situation in which your index.html file looks like this
```html
<html>
<head>
<!-- placeholder -->
</head>
<body>
<div id="root"></div>
</body>
</html>
```
You can then use custom transformer function to replace the HTML comment with any string you like. It can be a custom meta tag. You can use request object to extract additional information about request such as requested page.
```javascript
import express from "express";
import ViteExpress from "vite-express";
import someMiddleware from "./some/middleware";
const app = express()
function transformer(html: string, req: express.Request) {
return html.replace(
"<!-- placeholder -->",
`<meta name="custom" content="${req.baseUrl}"/>`
)
}
app.use(someMiddleware())
ViteExpress.config({ transformer })
ViteExpress.listen(app, 3000);
```
The HTML served to the client will then look something like this
```html
<html>
<head>
<meta name="custom" content="/"/>
</head>
<body>
<div id="root"></div>
</body>
</html>
```
## 🤔 How does it work?

@@ -184,6 +276,17 @@

| name | description | default | valid values |
| ---- | ----------------------------------------------------------------------------------------------------------------------------------- | ------------- | --------------------------- |
| mode | When set to development Vite Dev Server will be utilized, in production app will serve static files built with `vite build` command | `development` | `development`, `production` |
<<<<<<< HEAD
| name | description | default | valid values |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------- |
| mode | When set to development Vite Dev Server will be utilized, in production app will serve static files built with `vite build` command | `"development"` | `"development"` \| `"production"` |
| transformer | A function used to transform HTML served to the client, useful when you want to inject some metadata on the server. First argument is the HTML that is about to be sent to the client, second is the [`Request`][express-request] object. Needs to return transformed HTML as a string. | `undefined` | `undefined` \| `(html: string, req: Request) => string` |
| inlineViteConfig | When set to non-undefined value, `vite-express` will be run in [`viteless mode`](#-viteless-mode) | `undefined` | `undefined` \| `ViteConfig` |
```typescript
type ViteConfig = {
root?: string;
base?: string;
build?: { outDir: string };
}
```
### `listen(app, port, callback?) => http.Server`

@@ -253,1 +356,7 @@

[MIT](LICENSE)
[express-request]: https://expressjs.com/en/api.html#req
[vite-config]: https://vitejs.dev/config/
[root]: https://vitejs.dev/config/shared-options.html#root
[base]: https://vitejs.dev/config/shared-options.html#base
[outDir]: https://vitejs.dev/config/build-options.html#build-outdir
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