Eptagone / Vite.AspNetCore

Small library to integrate Vite into ASP.NET projects
MIT License
264 stars 35 forks source link

Custom directory configuration #123

Closed luylucas10 closed 4 months ago

luylucas10 commented 4 months ago

It's not an issue, it's a hint.

I like to use the default wwwroot directory for src and dist code, so I've created src folder under wwwroot, splitted in scss, js, img. For second, I like to read all file at once in the config, instead to set a array of input in the rolloup config. That way, my vite.config.js is that:

/**
 * Name: vite.config.ts
 * Description: Vite configuration file
 */

import {defineConfig} from "vite";
import {spawn} from "child_process";
import fs from "fs";
import path from "path";
import {fileURLToPath} from "url";
import {glob} from "glob";

// Get base folder for certificates.
const baseFolder =
    process.env.APPDATA !== undefined && process.env.APPDATA !== ""
        ? `${process.env.APPDATA}/ASP.NET/https`
        : `${process.env.HOME}/.aspnet/https`;

// Generate the certificate name using the NPM package name
const certificateName = process.env.npm_package_name;

// Define certificate filepath
const certFilePath = path.join(baseFolder, `${certificateName}.pem`);
// Define key filepath
const keyFilePath = path.join(baseFolder, `${certificateName}.key`);

// Export Vite configuration
export default defineConfig(async () => {
    // Ensure the certificate and key exist
    if (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) {
        // Wait for the certificate to be generated
        await new Promise((resolve) => {
            spawn("dotnet", [
                "dev-certs",
                "https",
                "--export-path",
                certFilePath,
                "--format",
                "Pem",
                "--no-password",
            ], {stdio: "inherit",})
                .on("exit", (code) => {
                    resolve();
                    if (code) {
                        process.exit(code);
                    }
                });
        });
    };

    // Define Vite configuration
    const config = {
        appType: "custom",
        root: "wwwroot/src",
        base: "/dist",
        build: {
            emptyOutDir: true,
            manifest: true,
            outDir: "../dist",
            assetsDir: "",
            rollupOptions: {
                input: Object.fromEntries(
                    glob
                        .sync("wwwroot/src/js/*.js")
                        .map(file => [file.split("/")[file.split("/").length - 1], fileURLToPath(new URL(file, import.meta.url))]),
                )
            }
        },
        server: {
            strictPort: true,
            https: {
                cert: certFilePath,
                key: keyFilePath
            }
        },
        optimizeDeps: {
            include: []
        },
        resolve: {
            alias: {
                '@': path.resolve(__dirname, 'wwwroot/src')
            }
        }
    }

    return config;
});

In appsettings:

  "Vite": {
    "Base": "/dist",
    "Server": {
      "AutoRun": true,
      "Port": 5173,
      "Https": true
    }
  }

and last app.UseViteDevelopmentServer(app.Environment.IsDevelopment());

That way, we have custom vite config working with default asp.net directory.