Skip to main content

CSS Import and Stylesheet Links

This guide demonstrates how to import CSS files from a package and return them as stylesheet links in a TypeScript project.

Installation

To use CSS imports, follow these steps:

  1. Install the necessary packages:

    npm install <your-css-package>
    # or
    yarn add <your-css-package>

Importing CSS Files

Method 1: Direct Import

Append ?url at the end of the CSS import:

import '<your-css-package>/any.css'

Method 2: Named Import with URL

Use a named import with ?url:

import mainStyles from '<your-css-package>/main.css?url';

Note: Add @ts-ignore above the import to avoid TypeScript errors:

//@ts-ignore
import mainStyles from '<your-css-package>/main.css?url';

Create a function to return stylesheet links:

//@ts-ignore
import mainStyles from '<your-css-package>/main.css?url';
//@ts-ignore
import customStyles from '../styles/landing.css?url';

export const links = () => {
return [
{
rel: 'stylesheet',
href: customStyles as unknown as string,
},
{
rel: 'stylesheet',
href: mainStyles as unknown as string,
},
];
};

Usage in Components

Route Component (app.tsx)

import { LinksFunction } from "remix";
import buttonStyles from "../styles/button.css?url";

export const links: LinksFunction = () => {
return [{ rel: "stylesheet", href: buttonStyles }];
};

import Button from "../components/Button";

const ComponentWithLoader = (props) => {
return (
<React.Suspense fallback={<Spinner />}>
<Await resolve={OwnerPropertiesLoader} errorElement={<Alert>Error loading TypeLists!</Alert>}>
<div>
<h1>Welcome to my Remix app!</h1>
<Button />
</div>
</Await>
</React.Suspense>
);
}

Subcomponent (Button.tsx)

export default function Button() {
return (
<button className="custom-button">Click me</button>
);
}

Troubleshooting

Error: No route matches URL "/styles/landing.css"

Ensure the styles folder is copied to the lib folder. Check rollup.config.base.mjs for the correct copy plugin configuration:

const additionalPlugins = [
copy({ patterns: ['**/cdm-locales/**/*', '**/styles/**/*'], rootDir: './src' }),
];

Build error: Could not resolve "../styles/landing.css?url"

Add the ignoreCssUrlPlugin to rollup.config.base.mjs after the typescript plugin:

// Add this import at the top of the file
import { ignoreCssUrlPlugin } from '@adminide/rollup-plugin-ignore-css-url';

// In the plugins array
plugins: [
// ... other plugins
typescript(),
ignoreCssUrlPlugin(),
// ... other plugins
]

By following these guidelines, you can effectively manage CSS imports and stylesheets in your TypeScript project.

Back to Index | Previous: Generated Data Loaders | Next: Component Structure Best Practices