Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React reusable component library styles not loading

hey people I need help with the following:

  • am creating React UI component library

  • I am using webpack and dev build works great, scss files are loaded and components are displayed correctly

  • on production build, JS bundle is created as well as CSS (I use SCSS) bundle

  • BUT when I install the library in another React project and import the component, CSS is not loaded (cmp is not styled), JS works fine and the component is rendered yet styles are not loaded...

EDIT Apparently this approach requires manual loading of CSS in parent app project. Which I want to avoid. Is there alternative way which can provide scenario in which styles will be resolved on the level on component without need for manual loading?

Here is my production webpack config:

const path = require('path');

const ExtractTextPlugin = require('extract-text-webpack-plugin');

const UglifyJsPlugin = require('uglifyjs-webpack-plugin');


module.exports = {

  entry: './src/index.js',

  output: {

    filename: 'bundle.js',

    path: path.join(__dirname, '../lib'),

    libraryTarget: 'commonjs',

  },

  module: {

    rules: [

      {

        test: /\.css$/,

        use: ExtractTextPlugin.extract({

          fallback: 'style-loader',

          use: ['css-loader']

        })

      },

      {

        test: /\.scss$/,

        use: ExtractTextPlugin.extract({

          fallback: 'style-loader',

          use: ['css-loader', 'sass-loader']

        })

      },

      {

        test: /\.js$/,

        exclude: /node_modules/,

        loader: "babel-loader"

      },

      {

        test: /\.svg/,

        use: {

          loader: 'svg-url-loader',

          options: {}

        }

      }

    ]

  },

  externals: {

    'react': 'commonjs react',

    'react-dom': 'commonjs react-dom',

  },

  resolve: {

    modules: [

      path.resolve('./src'),

      path.resolve('./node_modules')

    ]

  },

  plugins: [

    new ExtractTextPlugin({

      filename: 'ui-library.css'

    })

  ]

};
like image 859
Develoger Avatar asked Mar 06 '26 21:03

Develoger


1 Answers

You could simply not use ExtractTextPlugin.

The whole purpose of Webpack is to group assets not based on file type but by a component perspective.

So, if you remove ExtractTextPlugin, your CSS will be included in your .js bundle.

like image 153
Jalil Avatar answered Mar 08 '26 09:03

Jalil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!