Sid
Sid

Reputation: 1014

How to load CSS files with webpack

Im trying to have my CSS file in the src folder copied into the dist folder on build - Im currently using a HTML file in my dist - ie im not using a javascript file so dont want the styles to be created as javascript.I just need the files to be copied into the dist. Heres my current config that isnt working.

const htmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
    devServer:{
      port:8000
    },
    module: {
        rules: [
            {
                test: /\.html$/i,
                loader: 'html-loader',
            },
            {
              test: /\.css$/i,
              use: [ 'style-loader','css-loader'],
            },
            {
              test: /\.(png|jpe?g|gif|glb|gltf|typeface.json)$/i,
              loader: 'file-loader',
              options: {
                  publicPath: './',
                  name: '[name].[ext]'
              },
          },
        ]
    },
    plugins: [
        new htmlWebpackPlugin({
            template: './src/index.html',
            filename: './index.html'
        })
    ]
}

I then use a link tag to add the css into the index.html file eg

 <link rel="stylesheet" href="./style.css">

But this just adds javascript to the HTML file it builds in the dist.

How can i do this?

***EDIT: Im trying to add CSS files without merging them into my Javascript files

Upvotes: 1

Views: 3192

Answers (1)

Yusuf T.
Yusuf T.

Reputation: 980

You can try using MiniCssExtractPlugin. As written in the documentation:

This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.

To use it, you can first install it, import it, add a loader and a plugin to your webpack config. Here's an example (don't forget to note the order must be correct):

...
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  ...
  module: {
    rules: [
      ...
      {
        test: /\.css$/i,
        use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader'],
      },
      ...
    ],
  },
  plugins: [
    ...
    new MiniCssExtractPlugin(),
  ],
};

It will also add an automatic link tag to your css files in index.html results.

Upvotes: 0

Related Questions