Skip to content
Advertisement

Webpack, disable the export of assets referenced in SCSS/CSS

When running Webpack in development, it generates the correct bundle.js and style.css with source maps, but all the assets referenced in the SCSS files are copied to my Webpack output folder, along with a hash before them, like so:

enter image description here

Is there a way to disable the hashing & copying of assets for local development? I understand this for production but I don’t need it while developing. It also causes unstaged changes which become annoying.

My Webpack configuration is the following:

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

module.exports = (env, argv) => {

  const hash = generateHash();
  const production = argv.mode === 'production' ? true : false;

  var config = {
    entry: [
      './assets/scripts/src/index.ts',
      './assets/scss/src/style.scss'
    ],
    devtool: production ? false : 'inline-source-map',
    watch: production ? false : true,
    devServer: {
      watchContentBase: true
    },
    module: {
      rules: [
        {
          test: /.ts$/,
          use: 'ts-loader',
          exclude: /node_modules/,
        },
        {
          test: /.scss$/,
          use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            'sass-loader'
          ]
        }
      ]
    },
    resolve: {
      extensions: ['.ts', '.js'],
    },
    output: {
      filename: production ? `bundle.${hash}.min.js` : 'bundle.js',
      path: path.resolve(__dirname, 'wwwroot')
    },
    plugins: [
      new MiniCssExtractPlugin({
        filename: production ? `style.${hash}.min.css` : 'style.css'
      })
    ]
  };

  return config;
};

function generateHash() {
  var result = '';
  var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  var charactersLength = characters.length;
  for (var i = 0; i < 15; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

Advertisement

Answer

If you pass an options object with url: false to css-loader, it will stop importing those files. And since you want to disable only for development, you can use that production variable you have, like so:

 {
  test: /.scss$/,
  use: [
    MiniCssExtractPlugin.loader,
   {
      loader: "css-loader",
      options: {
        url: production,
      },
    },
    'sass-loader'
  ]
}
Advertisement