hope css code inject into html <style> when use vite build vue3 app

197 Views Asked by At

I use vite to build the vue3 app with an index.html, I hope the output HTML can contain the CSS code in the tab in the HTML file, rather than a CSS file <link> in it.

what should I do?

App.vue file code:

<script setup lang="ts">
import { ref } from 'vue';
import './app.css';

const count = ref(0);

function addCount() {
  count.value++;
}
</script>

<template>
  <button @click="addCount">{{ count }}</button>
  <div class="good">good</div>
  <img src="./20230707075538555-900x900.jpg" width="100" height="100" />
</template>

<style scoped>
.good {
  color: red;
}
</style>

I use createSSRApp to create the app.

index.html is simple

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
    <!--preload-links-->
  </head>
  <body>
    <div id="app"><!--app-html--></div>
    <script type="module" src="/src/entry-client.js"></script>
  </body>
</html>

I use vite to build, config:

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue"; //add this line

export default defineConfig({
    base: '/',
    build: {
      cssCodeSplit: false,
    },
    plugins: [
      vue(), // write this
    ],
});

finally, the output file code is :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
    <!--preload-links-->
    <script type="module" crossorigin src="/assets/index-d8e5f2e3.js"></script>
    <link rel="stylesheet" href="/assets/style-fac1f9f2.css">
  </head>
  <body>
    <div id="app"><!--app-html--></div>
    
  </body>
</html>

I hope it can replace the CSS with the tab containing CSS code.

I try importing separate CSS files in the <style scope> tab in the vue file or importing CSS files in the script. It didn't work.

and I try use this plugin in vite config:

import { libInjectCss } from 'vite-plugin-lib-inject-css';

bug it to throw an error during the build process。

error during build:

TypeError: Cannot convert undefined or null to object
0

There are 0 best solutions below