I have a public lib build by vite, now I want to import the css from the public lib:
import 'rd-component/dist/style.css';
but when I build the project, shows error:
ERROR in ./src/page/photo/gen/GenPhoto.tsx 18:0-37
Module not found: Error: Package path ./dist/style.css is not exported from package /Users/john/source/reddwarf/frontend/snap-web/node_modules/rd-component (see exports field in /Users/john/source/reddwarf/frontend/snap-web/node_modules/rd-component/package.json)
webpack compiled with 1 error and 1 warning
No issues found.
what should I do to export the css file? I have tried like this:
plugins: [
{
name: 'extract-css',
generateBundle(_, bundle) {
for (const fileName in bundle) {
const chunk = bundle[fileName];
if (fileName.endsWith('.js') && chunk.code.includes('import "./style.css";')) {
const cssFileName = fileName.replace('.js', '.css');
const css = chunk.code.match(/(?<=import ")[^"]+(?=";)/s)[0];
fs.writeFileSync(`dist/${cssFileName}`, css, 'utf-8');
chunk.code = chunk.code.replace(css, `./${cssFileName}`);
}
}
},
},
],
shows error that chunk did not contains code attribute. how to export the css from public lib and import from currrent project successfully? this is the node_modules of public lib:

Finally, I found I have to export the css like this in package.json:
"exports": {
".": {
"import": "./dist/rd-component.es.js",
"require": "./dist/rd-component.umd.js"
},
"./dist/style.css": {
"import": "./dist/style.css",
"require": "./dist/style.css"
}
},
more information from here: https://github.com/vitejs/vite/discussions/2657
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