Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Add Global CSS for All Modules in Development Server #96

Open
jason-rosterlab opened this issue Dec 11, 2024 · 1 comment
Open

Comments

@jason-rosterlab
Copy link

I’m looking for a way to add global CSS that applies to all modules in dev server (@hubspot/cms-dev-server), accessible at http://hslocal.net:3000/.

The global CSS should only be applied in the development server environment and not affect the deployed HubSpot modules. Specifically, I’d like to know:

  • How to import a CSS file (e.g., global.css) to be applied globally across all modules during development.
  • Where the entry point (e.g., App.js or index.js) of the dev server can be located. I've searched for this entry point in the dev server setup but have not been able to find it, which makes it unclear where global styles can be included.

Thank you

@DaniFrancisco
Copy link

DaniFrancisco commented Dec 13, 2024

hey @jason-rosterlab. I've bumped into the exact same problem. Unsure whether this is the best approach, but ended up adding a css preprocessor to the vite.config file. This preprocessor is responsible for appending the globals file to every module's css. It's only applied in development mode.

I'm using CSS modules + SCSS, here's my config:

import path from "path";

import merge from "lodash.merge";
import { defineConfig, UserConfig } from "vite";

const excludePath = (filePath: string) => (source: string, fp: string) => {
  if (fp.includes(filePath)) {
    return source;
  }

  return `@use "@/styles/globals.scss" as *; ${source}`;
};

const commonConfig: UserConfig = {
  css: {
    preprocessorOptions: {
      scss: {
        api: "modern",
      },
    },
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./"),
    },
  },
};

export default defineConfig(({ command }) => {
  if (command === "serve") {
    // development

    return merge(commonConfig, {
      css: {
        preprocessorOptions: {
          scss: {
            additionalData: excludePath("app/styles"),
          },
        },
      },
    });
  }

  // production

  return commonConfig;
});

additionalData: excludePath(...) is where the magic happens. I had to exclude the global styles path (app/styles) otherwise Vite would try to build those files as well and would cause infinite loops.

It's a bit hacky to be honest, but it has been working fine.

Hope it helps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants