Webpack - How to add a CSS file in the head of index.ejs?


#1

I’m trying to load a css file immediately to style a loading screen in my application.

Right now I have a style.css file included in main.js, but there is a noticeable delay between when the loading section is displayed and when the styles are applied.

How can I add this css file to the head of the index.ejs? I imagine I could use some kind of variable in the webpack.config.js file but I’m not sure how to set that up.

This is what I want to do:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title><%- htmlWebpackPlugin.options.metadata.title %></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <base href="<%- htmlWebpackPlugin.options.metadata.baseUrl %>">
    
    <!-- this doesn't work -->
    <link rel="stylesheet" href="src/css/style.css" />
    
    <!-- imported CSS are concatenated and added automatically -->
  </head>
  <body aurelia-app="main">
    <% if (htmlWebpackPlugin.options.metadata.server) { %>
    <!-- Webpack Dev Server reload -->
    <script src="/webpack-dev-server.js"></script>
    <% } %>
    
    <div id="splash-screen>
      ...
    </div>
    
  </body>
</html>

#2

Total hack but I just used CopyWebpackPlugin to copy the raw css file to the output folder.
If anybody finds a better way please let me know.

webpack.config.js

plugins: [
  ...
  new CopyWebpackPlugin([
      { from: 'src/css/style.css', to: 'style.css' }
  ])
]

index.ejs

<head>
  ...
  <link rel="stylesheet" href="style.css" />
  ...
</head>

#3

You need extract-text-webpack-plugin. It will extract CSS into a separate file and then html-webpack-plugin will generate html based on your ejs