I am creating a series of components to be reused in the company I work for. We use typescript and so far I can create the components properly, transpile to javascript, and publish to npm. I only use the command line tsc, I am not using webpack. My problem relies in a specific component that uses a css file. When I run the actual app that installs my npm package, it throws an error:
./~/my-common-components/dist/DataTable.js
Module not found: Can't resolve './DataTable.css' in '.\AdminPortal\admin-portal\node_modules\common-components\dist'
When I look at the dist folder of my transpiled code, the css file is not there.
I tried adding 'files' to the tsconfig.json file and it does add it, but with the exact same path (src\DataTable.css in stead of dist\DataTable.css)
Is there a way to include that file in the final package without using webpack?
First step — Importing css files in Typescript In order to do so your webpack configuration must have a loader for css files. I used css-loader for such. So you need to install it first with the command. Then you need to specify in you webpack configuration file in section module -> rules how CSS files will be loaded.
An NPM module must supply JavaScript (not TypeScript) code. It's important to provide JavaScript so the modules work with JavaScript projects.
The @import rule allows you to import a style sheet into another style sheet. The @import rule must be at the top of the document (but after any @charset declaration). The @import rule also supports media queries, so you can allow the import to be media-dependent.
Basically, tsc is designed to compile .ts / .tsx files and does not currently handle other file types such as .css. This is a known issue and is tracked here.
To get around the problem, you need to have tsc compile all of your TypeScript files and then copy over any non-TypeScript files. Víctor Colombo has a great guide to copying over .css files here. The two steps are listed below:
First, install two dev dependencies that will help with copying overfil
npm install --save-dev rimraf copyfiles
Then, update your "scripts" in package.json to implement the copying process for non-TypeScript files when the package is built:
"scripts": {
"clean": "rimraf dist/",
"copy-files": "copyfiles -u 1 src/**/*.html src/**/*.css dist/",
"build": "yarn clean && tsc && yarn copy-files"
},
Note: This solution assumes you are using npm although you can just as easily swap in yarn as your package manager. It also assumes that distribution files are stored in a dist folder. You can check if the solution is working by running npm run build and checking for the .css files under dist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With