0

For 2 days I have been trying to compile the js and css file to a separate file because now everything is together. Does anyone have any idea how this can be solved? I would be very grateful for your help.

There is my code webpack.config.js

const path = require('path');
const webpack = require('webpack');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');

module.exports = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'src/dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            {
                test: /\.scss$/,
                use: [
                    "style-loader", // creates style nodes from JS strings
                    {
                        loader: "css-loader",
                        options: {
                            url: false
                        }
                    },
                    "sass-loader" // compiles Sass to CSS, using Node Sass by default
                ]
            },
        ]
    },
    plugins: [
        new BrowserSyncPlugin({
        // browse to http://localhost:3000/ during development,
        // ./public directory is being served
            host: 'localhost',
            port: 3000,
            files: ['./src/*.html'],
            server: { baseDir: ['src'] }
        }),
    
     new webpack.ProvidePlugin({
       $: 'jquery',
       jQuery: 'jquery'
     })
 
    ]
};
user11656141
  • 51
  • 1
  • 4
  • Does this answer your question? [Can I use webpack to generate CSS and JS separately?](https://stackoverflow.com/questions/35322958/can-i-use-webpack-to-generate-css-and-js-separately) – Marco Bonelli Aug 07 '20 at 11:05

1 Answers1

0

I think MiniCssExtractPlugin is what you are looking for.

It takes the output of css-loader and create .css bundles. It takes care of downloading them in the browser (by pushing a section of code in webpack runtime code), and also yeah, it minifies the .css :).

Simple usage:

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

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

Yes you are right. Style-loader creates javascript snippets that later in runtime creates .css rules and push them to the browser global css scope.

Raz Ronen
  • 2,418
  • 2
  • 14
  • 26