CSS Import and Stylesheet Links Example
This example demonstrates how to import CSS files from a package and return them as stylesheet links in a TypeScript project.
Installation
To use this example, follow these steps:
Install the necessary packages:
npm install <your-css-package>
# or
yarn add <your-css-package>
Import the CSS files in your TypeScript file:
append the ?url at the end of css import
import mainStyles from '<your-css-package>/main.css?url';
or
import '<your-css-package>/any.css'
Add @tsignore above import
//@ts-ignore
import mainStyles from '<your-css-package>/main.css?url';
Define 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,
},
];
};
Note: All css files import should be in route component, in subcomponent components it will not work
Directory Structure
app routes app.tsx components Button.tsx styles app.css button.css
app.tsx (Route Component)
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></Spinner>}>
<Await resolve={OwnerPropertiesLoader} errorElement={<Alert>Error loading TypeLists!</Alert>}>
<div>
<h1>Welcome to my Remix app!</h1>
<Button />
</div>
</Await>
</React.Suspense>
);
}
Button.tsx (SubComponent)
export default function Button() {
return (
<button className="custom-button">Click me</button>
);
}
Troubleshoot
Error: No route matches URL "/styles/landing.css"
Make sure styles
folder which it is looking is copied to lib
folder. If not check rollup.config.base.mjs
under root of the project, whether it has styles
pattern in copy plugin
const additionalPlugins = [
copy({ patterns: ['**/cdm-locales/**/*', '**/styles/**/*'], rootDir: './src' }),
];
Build error: [!] RollupError: Could not resolve "../styles/landing.css?url" from "src/pages/Landing.tsx"
Make sure ignoreCssUrlPlugin
added to rollup.config.base.mjs
after typescript
plugin as shown below.