Damian Jacobs
Damian Jacobs

Reputation: 538

Adding styling to TypeScript, React NPM package

I have a TypeScript(TS), React project which I'm using to hold all my React components. I'm creating an NPM package out of this project which I'm then consuming in separate React projects. I'm running into a problem where I don't know how to export the styling along with the TS components.

Using components from the NPM package result in errors: Module not found: Can't resolve '../css/footer.css'

When I create my directory for packaging(dist) all my components are there but none of the CSS. I'm running tsc to create this directory. All my components and CSS lie within the same src folder.

Here is my tsconfig.json file:

{
  "compilerOptions": {
    "outDir": "dist",
    "target": "esnext",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react"
  },
  "include": [
    "src"
  ]
}

Do I need to move my styling out of css files and into ts files that make use of the <style jsx> tag or is there another 'better' way of achieving the desired result. The desired result being an NPM package that contains all styling and components rolled into one.

Upvotes: 2

Views: 1591

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

tsc is the command for compiling TypeScript files to Javascript. CSS files are not Typescript files which is why they aren't included in the compilation.

If you want to import CSS (or any other asset types) and output it alongside your other compiled files then you'll probably want to use a bundler like Webpack or Rollup. There are even tools like Microbundle which provide sensible bundler configuration so that you can focus on writing your library.

Alternatively, you could write your styles in TypeScript too, with a library like styled-jsx.

Even if you're not interested in using one, it's worth taking a look at the various templates for TypeScript + React npm packages to see how they work.

Upvotes: 2

Related Questions