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?
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
.