Skip to content

Inlining CSS and JS in HTML does not work #8397

@mindplay-dk

Description

@mindplay-dk

Describe the bug

I am attempting to migrate my project from Parcel to Vite.

My project is a single-page application.

For easy deployment and fast startup, my project is designed to ship as a single .html file with all JS and CSS inlined in the HTML page.

The problems described here pertain to the production build for an index.html like the following:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      @import './style.scss';
    </style>
  </head>
  <body>
    <script type="module">
      import '/main.js';
    </script>
  </body>
</html>

1. @import from .scss files in <style> tags doesn't work

With Parcel, I was able to achieve this with an inline @import for the CSS:

Note that I'm attempting to use SASS here.

Unfortunately, this does not seem to work in Vite, where the inline <style> tag appears to be handled without any module processing, based on the file extension. (?)

The resulting output from this example is e.g.:

<style>
  @use "app";
</style>

So the .scss file does not get processed.

Things I've tried that didn't work:

  • 👎 @import url('./style.scss') (same)
  • 👎 <style type="sass"> (same)
  • 👎 <style lang="sass"> (probably only works for Vue)

My current workaround is to use an external CSS file.

2. import from <script> tags doesn't work as expected

Having used an inline <script type="module">, I would expect the code within that tag to get bundled an inlined, as I was able to do with Parcel.

Instead, the inline script tag is removed from <body>, and an external script tag is inserted into <head> - this will execute before the DOM is ready, will block the page from rendering, and so on.

There is no workaround for this one - I will get an external .js file no matter what.

Summary

I wanted one HTML file, but I'm getting 3 separate assets (HTML, CSS, JS) instead.

What happens at development time isn't important, but it doesn't look like the production build I wanted is currently possible with Vite?

Reproduction

https://stackblitz.com/edit/vitejs-vite-gv7uz4?file=index.html

System Info

System:
    OS: Linux 5.10 Ubuntu 16.04.7 LTS (Xenial Xerus)
    CPU: (8) x64 Intel(R) Core(TM) i7-4790K CPU @ 4.00GHz
    Memory: 4.85 GB / 6.13 GB
    Container: Yes
    Shell: 4.3.48 - /bin/bash
  Binaries:
    Node: 16.14.2 - ~/.nvm/versions/node/v16.14.2/bin/node
    Yarn: 1.22.4 - ~/.npm-global/bin/yarn
    npm: 8.5.5 - ~/.npm-global/bin/npm
  npmPackages:
    vite: ^2.9.9 => 2.9.9 

Used Package Manager

npm

Logs

(reproduction provided above - let me know if you need this.)

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions