Webpack collected files (.css, .js) into a library and use it in another React project. The styles specified in the component do not pass, although the .css file is present and the styles are there.
UiButton.jsx file
import styles from './UiButton.module.css';
const UiButton = () => {
return (
<>
<button className={styles.button}>Text</button>
</>
);
}
export default UiButton;
index.js file
import UiButton from './UiButton/UiButton';
import './index.css';
export { UiButton };
Webpack.config.js file
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: { main: './src/index.js' },
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
libraryTarget: "umd",
library: "uilibrarytest"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [ 'style-loader', MiniCssExtractPlugin.loader, 'css-loader' ]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'index.css',
}),
// new HtmlWebpackPlugin({
// template: './public/index.html',
// }),
new webpack.ProvidePlugin({
"React": "react",
}),
],
resolve: {
extensions: ['.js', '.jsx'],
},
}
This is what webpack builds:
.button {
background: red;
}
html {
margin: 0;
padding: 0;
}
How to make it so that when using a component from a given library, the styles are also pulled to it ???
CodePudding user response:
Loaders in Webpack are evaluated from right to left. In your configuration the evaluation order is 'css-loader', MiniCssExtractPlugin.loader, and finally 'style-loader'. But 'style-loader' only injects styles into the DOM. You need MiniCssExtractPlugin.loader to be the first element in the "use" array. See below...
{
test: /\.css$/,
use: [ MiniCssExtractPlugin.loader, 'css-loader' ]
}
Furthermore you can tell webpack to use MiniCssExtractPlugin.loader during production and at other times use 'style-loader'.
const isProduction = process.env.NODE_ENV == 'production';
const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';
...other config
{
test: /\.css$/,
use: [ stylesHandler, 'css-loader' ]
}
And in your package.json scripts,
"build": "webpack --mode=production --node-env=production"