I’m transpiling a React component library into UMD using Webpack (Babel, etc.). The components load just fine in a local Storybook instance, but when I import them into a new create-react-app project, none of the styles load…or classes for that matter. I can see what appears to be the CSS and class names in the built JS file, but the elements in the DOM look like this when inspected:
<h1 class>Hello World!</h1>
Is there a trick to getting them to load? I’ve tried just about every possible Webpack configuration I could come up with to no avail. Regardless, here are some of the files in question:
Library/webpack.config
module.exports = {
entry: {
HelloWorld: './src/components/HelloWorld/index.js',
},
externals: {
'react': 'react',
'react-dom': 'react-dom',
},
mode: 'production',
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env',
[
'@babel/preset-react',
{
runtime: 'automatic',
},
],
],
},
},
},
{
test: /.module.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
{
test: /.(png|jpg)$/,
exclude: /node_modules/,
loader: 'file-loader',
options: {
outputPath: (url, resourcePath, context) => {
const componentName = resourcePath.replace(context, '').split('/')[3];
return `${componentName}/${url}`;
},
},
},
{
test: /.svg$/,
exclude: /node_modules/,
loader: '@svgr/webpack',
options: {
exportType: 'named',
},
}
],
},
output: {
filename: '[name]/index.js',
library: {
type: 'umd',
},
path: `${__dirname}/build`,
},
};
Library/package.json
{
...
"exports": {
"./HelloWorld": "./build/HelloWorld/index.js"
}
...
},
}
Library/src/components/HelloWorld/index.js
import styles from './HelloWorld.module.css';
export default function HelloWorld() {
return {
<h1 className={styles.helloWorld}>Hello World!</h1>
}
}
Library/src/components/HelloWorld/HelloWorld.module.css
.helloWorld {
color: red;
}
Project/src/App/index.js
import HelloWorld from 'my-library/HelloWorld';
export default function App() {
return (
<HelloWorld />
)
}