How to import style with webpack?

by lindsey.homenick , in category: Javascript , 6 months ago

How to import style with webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 6 months ago

@lindsey.homenick 

To import CSS files and apply styles to your web application using webpack, you can follow these steps:

  1. Install necessary loaders: Make sure you have the necessary loaders installed in your project to handle CSS files. You will need style-loader and css-loader.
1
npm install style-loader css-loader --save-dev


  1. Configure webpack: In your webpack.config.js file, add a module rule to handle CSS files using the loaders.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
module.exports = {
  module: {
    rules: [
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
};


  1. Import CSS in your JavaScript file: Now, you can import CSS files directly in your JavaScript files. For example:
1
import './styles.css';


  1. Run webpack: Run webpack to build your application and apply the styles to your web pages.
1
npx webpack --config webpack.config.js


After following these steps, your CSS styles should now be applied to your web application when using webpack.