2

I'm using this solution: https://stackoverflow.com/a/45452306/417620. It works great, but the CSS content that is returned has comments and is not minified.

module: [
    rules: [
      {
        test: /\.css$/,
        use: ['to-string-loader', 'css-loader']
      }
    ]
  }

I'm using webpack 4. I've tried to use a number of different loaders, but they seem to no longer work with webpack 4 or they only work when the CSS is exported to a file. Is there anyway to remove the CSS comments and minify the CSS that is returned?

Here is the js that is returning the CSS as a string. import myCss from './myCss.css';

Jamin
  • 91
  • 3
  • 7

2 Answers2

3

You need to give minimize option true to your css-loader

module: [
    rules: [
        {
          test: /\.css$/,
          use: [
            {
              loader: "to-string-loader",
            },
            {
              loader: "css-loader",
              options: { minimize: true },
            },
          ],
       }
    ]
  }

to-string-loader will help to convert it to string. Minification will be taken care by css-loader.

Hope it helps. Revert for any doubts.

Sunil Chaudhary
  • 4,481
  • 3
  • 22
  • 41
  • 2
    This does work if you use css-loader v1. In v2 css-loader has removed the option to minimize. Any idea how to make this work in the newest version or what the plan is moving forward? – Jamin Mar 04 '19 at 17:33
  • Also this doesn't remove comments from the CSS. Any options on removing comments? – Jamin Mar 04 '19 at 17:34
2

I was able to resolve the issue using postcss-loader.

 module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          "to-string-loader",
          "postcss-loader",
        ],
      },
    ],
  },

Reference https://webpack.js.org/loaders/postcss-loader/

Jamin
  • 91
  • 3
  • 7
  • This answer partially gets you there. You also need to make sure you install postcss and cssnano as dev dependencies and also to reference them in your package.json ``` "postcss": { "map": false, "plugins": { "cssnano": {} } }, ``` – Glen Sep 05 '19 at 09:53