Skip to content

[2.0.5] css-loader: modules not working as needed after upgrade #232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
carlitux opened this issue May 12, 2017 · 34 comments
Closed

[2.0.5] css-loader: modules not working as needed after upgrade #232

carlitux opened this issue May 12, 2017 · 34 comments
Assignees

Comments

@carlitux
Copy link

css modules inside node_modules are working but css modules on my source are not added but loaded.

css is missed

require('babel-polyfill');
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const FlowtypePlugin = require('flowtype-loader/plugin');
const assetsPath = path.resolve(__dirname, '../static/dist');
const host = (process.env.HOST || 'localhost');
const port = (+process.env.PORT + 1) || 4001;

const rootPath = path.join(__dirname, './..');
const nodeModulesPath = path.join(rootPath, 'node_modules');

// Isomorfic Tools
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
const WebpackIsomorphicToolsPlugin =
  require('webpack-isomorphic-tools/plugin');
const webpackIsomorphicToolsPlugin =
  new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

// Babel config update to for client

const babelrc = fs.readFileSync('./.babelrc');
let babelrcObject = {};

try {
  babelrcObject = JSON.parse(babelrc);
} catch (err) {
  console.error('==>     ERROR: Error parsing your .babelrc.');
  console.error(err);
}

const babelrcObjectDevelopment =
  babelrcObject.env && babelrcObject.env.development || {};

// merge global and dev-only plugins
let combinedPlugins = babelrcObject.plugins || [];
combinedPlugins = combinedPlugins.concat(babelrcObjectDevelopment.plugins);

const babelLoaderQuery = Object.assign(
  {},
  babelrcObjectDevelopment,
  babelrcObject,
  { plugins: combinedPlugins }
);

delete babelLoaderQuery.env;

// Since we use .babelrc for client and server, and we don't want HMR enabled
// on the server, we have to add the babel plugin react-transform-hmr manually
// here.

// make sure react-transform is enabled
babelLoaderQuery.plugins = babelLoaderQuery.plugins || [];
let reactTransform = null;
for (let i = 0; i < babelLoaderQuery.plugins.length; ++i) {
  let plugin = babelLoaderQuery.plugins[i];
  if (Array.isArray(plugin) && plugin[0] === 'react-transform') {
    reactTransform = plugin;
  }
}

babelLoaderQuery.presets =
  babelLoaderQuery.presets.map(function (item) {
    if (item === 'es2015') {
      return ['es2015', { modules: false }];
    }
    return item;
  });

if (!reactTransform) {
  reactTransform = ['react-transform', {transforms: []}];
  babelLoaderQuery.plugins.push(reactTransform);
}

if (!reactTransform[1] || !reactTransform[1].transforms) {
  reactTransform[1] = Object.assign({}, reactTransform[1], {transforms: []});
}

module.exports = {
  entry: {
    vendor: require('./vendorList'),
    main: [
      'react-hot-loader/patch',
      //activate HMR for React

      'webpack-hot-middleware/client?path=http://' + host + ':' + port + '/__webpack_hmr',

      './src/client.js'
      //the entry point of our app
    ],
  },

  output: {
    path: assetsPath,
    filename: '[hash]-[id].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: 'http://' + host + ':' + port + '/assets/',
  },

  context: path.resolve(__dirname, '..'),

  devtool: 'inline-source-map',

  performance: { hints: false },

  module: {
    rules: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: [
        'react-hot-loader/webpack',
        'babel-loader?' + JSON.stringify(babelLoaderQuery),
        'eslint-loader',
        // 'flowtype-loader',
      ],
    }, {
      test: /\.json$/,
      loader: 'json-loader',
    }, {
      test: /\.css$/,
      use: [
        'style-loader',
        {
          loader: 'css-loader',
          options: {
            sourceMap: true,
            localIdentName: '[local]___[hash:base64:5]',
            importLoaders: 2,
            modules: true,
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            plugins: (loader) => [
              require('postcss-import')({
                root: loader.resourcePath,
              }),
              require('postcss-mixins')(),
              require('postcss-each')(),
              require('postcss-cssnext')({
                features: {
                  customProperties: {
                    variables: require('../src/theme/variables.js'),
                  }
                }
              }),
            ],
          } ,
        },
      ]
    }, {
      test: /\.(graphql|gql)$/,
      exclude: /node_modules/,
      loader: 'graphql-tag/loader',
    }, {
      test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
      loader: 'url-loader?limit=10000&mimetype=application/font-woff',
    }, {
      test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
      loader: 'url-loader?limit=10000&mimetype=application/font-woff',
    }, {
      test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
      loader: 'url-loader?limit=10000&mimetype=application/octet-stream',
    }, {
      test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
      loader: 'file-loader',
    }, {
      test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
      loader: 'url-loader?limit=10000&mimetype=image/svg+xml',
    }, {
      test: webpackIsomorphicToolsPlugin.regular_expression('images'),
      loader: 'url-loader?limit=10',
    }],
  },

  resolve: {
    modules: [
      'src',
      'node_modules'
    ],
    extensions: ['.json', '.js', '.jsx', '*'],
  },

  plugins: [
    // new FlowtypePlugin(),

    new webpack.LoaderOptionsPlugin({
      options: {
        context: path.resolve(__dirname, '..'),
      }
    }),

    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'], // Specify the common bundle's name.
    }),

    new webpack.HotModuleReplacementPlugin(),
    //activates HMR

    new webpack.NamedModulesPlugin(),
    //prints more readable module names in the browser console on HMR updates
    //
    new webpack.IgnorePlugin(/webpack-stats\.json$/),

    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: true,
      __DEVTOOLS__: true  // <-------- DISABLE redux-devtools HERE
    }),

    webpackIsomorphicToolsPlugin.development()
  ],
};
@michael-ciniawsky
Copy link
Member

Maybe because you are setting context in LoaderOptionsPlugin (not supportd by postcss-loader >= v2.0.0) anymore.

@michael-ciniawsky
Copy link
Member

michael-ciniawsky commented May 12, 2017

Which CSS is missing (from @import only or all CSS) ?
CSS Modules from src or node_modules, please elaborate further on this 😛

@michael-ciniawsky
Copy link
Member

Maybe releated to #222 (needs more info)

@carlitux
Copy link
Author

Which CSS is missing (from @import only or all CSS) ?
CSS Modules from src or node_modules, please elaborate further on this 😛

css modules from src are not in css bundle.

Maybe because you are setting context in LoaderOptionsPlugin (not supportd by postcss-loader

= v2.0.0) anymore.

I was thinking same but how could I do same without context option?

@michael-ciniawsky
Copy link
Member

michael-ciniawsky commented May 12, 2017

...
plugins: (loader) => { loader.context } // it should be there already
...

What it's purpose atm? I couldn't really reason about, where it actually gets used? :)
When you disable postcss-loader CSS Modules work ? This is odd, because they get generated by css-loader which runs after postcss-loader, could you post 1-2 components which import CSS ?

@michael-ciniawsky michael-ciniawsky changed the title Upgrade from 1.3.3 to 2.0.5 not working as needed [2.0.5] css-loader: modules not working as needed after upgrade May 13, 2017
@olegstepura
Copy link

Hi!

I did not investigate too deep, but after upgrade from 1.x to 2.0.5 version animations are broken in a project with react-toolbox (2.0 beta).

I can confirm that it's exactly the upgrade of postcss-loader breaks it. In my case it's an upgrade from 1.3.3 to 2.0.5.

But seems like there are some improvements as well, since build is now way smaller (1.1 Mb with 2.0.5 vs
1.5 Mb with 1.3.3) Previously I noticed lots of unprocessed postcss code in a build. Currently there are some sourcemaps inside build, but maybe it's my fault of misconfiguration.

So I assume you optimized importing logic, but looks like optimizations were too hard =) It's a pity i cannot upgrade due to the mentioned issue.

@alexander-akait
Copy link
Member

@olegstepura can your provide minimal reproducible test repo?

@michael-ciniawsky
Copy link
Member

@olegstepura I need your more info on how you utilise the lib (source files, webpack.config.js, [postcss.config.js]), normally postcss-loader doesn't alter anything 'unexpected' without the plugins you use :). The biggest improvement was to not generate a sourcemap by default anymore and cleanup some old API's (webpack && PostCSS). v2.0.0 uses PostCSS v6 (breaking change), so please check if your plugins are yet compatible with v6 by now, e.g cssnext isn't atm and maybe you need to manually update some plugins due to semver range in package.json

@olegstepura
Copy link

Hi, @michael-ciniawsky!

Thanks for your response. Here are my config files: gist

In build.js I've placed some code in which you can see that sources are still included (I would like to remove it, but sourceMap: true in postcss.config.js does not seem to help).

@evilebottnawi I will try to prepare test repo.

@olegstepura
Copy link

olegstepura commented May 17, 2017

Here is my test repo with react-toolbox: olegstepura/postcss-loader-test

The only change between two versions below is an edit in package.json:

-    "postcss-loader": "^1.3.3",
+    "postcss-loader": "^2.0.5",

And run npm i inside test repo folder after edit.

With version 1.3.3:

Big screen, everything is stacked good (click to see screenshot)

2017-05-17 11_52_15-test

Small screen, animation is smooth (click to see gif)

940f45f3008aaed768ae5d0d39f216bf

With version 2.0.5:

Big screen, strange spacing between navbar and appbar (click to see screenshot)

2017-05-17 11_56_14-test

Small screen (click to see gif and comments)
  • animation is broken: fade out first, no transition animation of nav bar, it just disappears.
  • icon color is also wrong (black instead of white)

87e299ea8ba4172b6a58865cc7b9c9c3

@olegstepura
Copy link

olegstepura commented May 17, 2017

Also I would love to hear any suggestion on how to remove source maps from build.js in my test repo.
npm run build produces src/main/webapp/asset/test.js
inside of that there is such content (with postcss-loader version 2.0.5, I inserted some newlines to make it more visually readable)

// ..
{"
.M7gDzYJNjHIL0YutSEctg :before{-webkit-touch-callout:none}._3pcMeyQKXVxkWHxAmg7hCU{background:rgba(97,97,97,.9);border-radius:2px;color:#fff;display:block;padding:8px}",
"",
{version:3,
sources:["c:/Temp/test/postcss-loader-test/node_modules/react-toolbox/lib/tooltip/theme.css"],
names:[],
mappings:"AAAA,+CACI,0DAA2D,AACnD,kDAAmD,AAE3D,0BACE,0DAA2D,AACnD,iDAAmD,CAC5D,CACJ,AAED,+CACI,8DAA+D,AACvD,sDAAuD,AAE/D,0BACE,8DAA+D,AACvD,qDAAuD,CAChE,CACJ,AAED,6CACI,8DAA+D,AACvD,sDAAuD,AAE/D,0BACE,8DAA+D,AACvD,qDAAuD,CAChE,CACJ,AAED,+CACI,4CAA6C,AACrC,mCAAqC,CAChD,uBACC,cAAe,AAEf,eAAgB,AAChB,gBAAiB,AACjB,iBAAkB,AAClB,gBAAiB,AACjB,YAAa,AACb,oBAAqB,AACrB,kBAAmB,AACnB,kBAAmB,AACnB,oBAAqB,AACrB,4CAA6C,AACrC,oCAAqC,AAC7C,kCAAmC,AAC3B,0BAA2B,AACnC,iDAAyD,AACzD,YAAa,AAEX,6CAAwD,CAM3D,AAED,6GATI,sBAAuB,AAEvB,mCAAoC,AACpC,2BAA4B,AAC5B,8BAA+B,AAC3B,0BAA2B,AACvB,qBAAsB,CAajC,AAVD,sFASM,0BAA4B,CACjC,AACD,yBACE,6BAAkC,AAClC,kBAAmB,AACnB,WAA0B,AAC1B,cAAe,AACf,WAAa,CACd",
file:"theme.css",
sourcesContent:[".tooltip.tooltipRight {\n    -webkit-transform: scale(0) translateX(0) translateY(-50%);\n            transform: scale(0) translateX(0) translateY(-50%);\n\n    &.tooltipActive {\n      -webkit-transform: scale(1) translateX(0) translateY(-50%);\n              transform: scale(1) translateX(0) translateY(-50%);\n    }\n}\n\n.tooltip.tooltipLeft {\n    -webkit-transform: scale(0) translateX(-100%) translateY(-50%);\n            transform: scale(0) translateX(-100%) translateY(-50%);\n\n    &.tooltipActive {\n      -webkit-transform: scale(1) translateX(-100%) translateY(-50%);\n              transform: scale(1) translateX(-100%) translateY(-50%);\n    }\n}\n\n.tooltip.tooltipTop {\n    -webkit-transform: scale(0) translateX(-50%) translateY(-100%);\n            transform: scale(0) translateX(-50%) translateY(-100%);\n\n    &.tooltipActive {\n      -webkit-transform: scale(1) translateX(-50%) translateY(-100%);\n "
]}    
// ...

this clearly states that there are source maps inside, which just make build heavier. I'm not even sure if this can somehow help debugging

@alexander-akait
Copy link
Member

@olegstepura without minimal repo we can't do anything, seems your use postcss plugins based on postcss v5, new loader working on v6, also seems sorceMap: false don't using in loader options.

@alexander-akait
Copy link
Member

@olegstepura oh, sorry don't saw your test repo 😄 let's see what is wrong

@alexander-akait
Copy link
Member

alexander-akait commented May 17, 2017

@olegstepura

  1. Some plugins don't compatibility with postcss-loader v2 (new loader use postcss v6)
  • postcss-each
  • postcss-cssnext
    The problems in markup (space) are related to this. Don't use this loader with plugins used postcss v5, need update all postcss plugins to compatibility with v6
  1. Source map
{
    loader: 'postcss-loader',
    options: {
        sourceMap: false
    }
}

Please, use the search before writing about the problem. Thanks!

@michael-ciniawsky
Copy link
Member

michael-ciniawsky commented May 17, 2017

@carlitux See #222 (comment), but feel free to reopen if still regressions

@olegstepura See @evilebottnawi comments, the only postcss-loader related issue is that { sourceMap: true || 'inline' } needs to be in webpack.config,js, bc postcss.config.js 'only' supports 'pure' PostCSS (Plugins && Options) Config, since it's used as a common config format one can use across different build tools (CLI, grunt, gulp, webpack) with any changes

Please update webpack v2.2.0-rc6 to the lastest version available 😉

@olegstepura
Copy link

olegstepura commented May 18, 2017

@evilebottnawi, @michael-ciniawsky thanks. I used search, that was how I found this issue not opened by me.

The problems in markup (space) are related to this.

So the animation problems are related to this as well, right?
Best solution? Wait while all the plugins will support PostCSS v6?

@olegstepura
Copy link

olegstepura commented May 18, 2017

About sourceMaps:
So I made this change: changeset (added sourceMap: false to webpack.config.js)
If I run npm run build final built file is 1.6Mb
If I remove this back to just string with the loader name, and run npm run build again final built file is 0.8Mb
It becomes even heavier with this change.

Sourcemaps stuff is complex, sorry to bother you.

Use case 1: I do not want source maps for CSS

  • I perform this changes
  • npm run build
  • bult file has sources! And it's size is 971kb.

Ok, maybe some PostCSS config should be added.

  • Add some config to postcss.config.js: changeset
  • npm run build
  • bult file has sources! And it's size is still 971kb.

Use case 2: I want source maps to be stored in separate build.js.map file. This would be usefull to debug production build one day.

  • I perform
- sourceMap: false
+ sourceMap: true

see this changeset

  • npm run build
  • bult file has sources! Sources are not in .map file (maybe there as well) And built file is 1.23 MB

I'm kind of lost... Am I doing something wrong? What is going on with sourceMaps? I tried to remove postcss-each and postcss-cssnext since you wrote these do not support PostCSS v6, but result is the same: if I disable sourcemaps, there are sources in built file (all those --palette-grey-300:#e0e0e0;--palette-grey-400:#bdbdbd;--palette-grey-500:#9e9e9e;) and it's size is 971kb.

Please help me figuring out on how to manage sourceMaps, I've read this guide and your README section according source maps. Nothing helps.

Thanks!

@michael-ciniawsky
Copy link
Member

devtool: 'sourcemap',
output: {
  filename: '[name].js',
  sourceMapFilename: '[name].js.map'
}

Output

@olegstepura
Copy link

olegstepura commented May 18, 2017

@michael-ciniawsky This is exactly (except of sourceMapFilename which is generated by default with this naming pattern) what I got in my test repo. Build file contains CSS sources, CSS sources are not in .map file (actually it may be in .map as well)

@felixsanz
Copy link

My CSS Modules also stopped working with css-loader 2.x. Heres my webpack config:

import path from 'path'
import fs from 'fs'

const externals = fs.readdirSync('node_modules')
  .filter((file) => !file.includes('.bin'))
  .map((name) => ({ [name]: `commonjs ${name}` }))
  .reduce((prev, curr) => ({ ...prev, ...curr }))

const defaultConfig = {
  context: path.resolve(__dirname, '..'),
  entry: './src/server',
  externals,
  node: {
    __dirname: true,
  },
  target: 'node',
  output: {
    path: path.resolve(__dirname, '..', 'dist'),
    filename: 'server.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [{
          loader: 'babel-loader',
        }],
        exclude: [
          path.resolve(__dirname, 'node_modules'),
        ],
      },
      {
        test: /\.css$/,
        use: ExtractTextWebpackPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
              query: {
                modules: true,
                importLoaders: 1,
                localIdentName: '[local]-[hash:base64:5]',
              },
            },
            {
              loader: 'postcss-loader',
            },
          ],
        }),
      },
    ],
  },
  plugins: [
    new ExtractTextWebpackPlugin({
      filename: 'styles.css',
      ignoreOrder: true,
    }),
  ],
  devtool: 'cheap-module-eval-source-map',
}

export default defaultConfig

Any idea why this happens?

@alexander-akait
Copy link
Member

@felixsanz Why do you duplicate it? It is create noise, just wait for someone to get free, also you can try to find the problem yourself and describe where it was found it will speed up the solution

@felixsanz
Copy link

felixsanz commented May 18, 2017

@evilebottnawi I'm not duplicating anything, i just moved my conversation here to avoid polluting the other issue :/

Notice that i deleted my message from the other issue. Sorry if it triggered notfiications

@alexander-akait
Copy link
Member

alexander-akait commented May 18, 2017

@felixsanz It would also be nice to see minimal test reproducible repo, it is difficult say that it is wrong just the configuration

@alexander-akait
Copy link
Member

alexander-akait commented May 18, 2017

@felixsanz just create new issue with minimal repo and what your expected and actually output. Please don't write your problems in closed issue

@felixsanz
Copy link

felixsanz commented May 18, 2017

@evilebottnawi I tried to create one reproducible test case but i don't even know what i'm supposed to reproduce. I don't understand whats going on, i just see that many rules just dissappeared while others are just there.

Open it then please? It's clearly not fixed

@alexander-akait
Copy link
Member

@felixsanz yep create new issue and try to show what is wrong (screenshots, console, example of code and etc.). Don't write here otherwise the problem may not be noticed.

@michael-ciniawsky
Copy link
Member

@felixsanz The only obvious thing I can see is (but likely unrelated)

{
   loader: 'css-loader',
-  query: {
+  options: {
      modules: true,
      importLoaders: 1,
      localIdentName: '[local]-[hash:base64:5]',
    },
}

What how does your current postcss.config.js look like ? Maybe try without importLoaders and @import, otherwise the CSS Modules implementation is independent from postcss-loader it must be a bug somewhere else, which surfaces via modules

@michael-ciniawsky
Copy link
Member

michael-ciniawsky commented May 19, 2017

I don't understand whats going on, i just see that many rules just dissappeared while others are just there.

Your postcss plugin versions package.json aswell please. postcss-loader >= v2.0.0 uses PostCSS v6 (breaking change) not all plugins support it yet, e.g if you use cssnext and it's nesting plugin, your rules are off, could be missing etc. atm

@felixsanz
Copy link

felixsanz commented May 19, 2017

@michael-ciniawsky It was working fine with 1.3.3. So the bug was introduced with postcss-loader 2.x, directly or indirectly.

My .postcssrc is this:

{
  "plugins": {
    "postcss-import": {}
  }
}

@michael-ciniawsky
Copy link
Member

The version of postcss-import is >= 10.0.0 ?

@michael-ciniawsky
Copy link
Member

Please also provide an input -> output example

@felixsanz
Copy link

I'll try create a testcase, but I spent an hour before with no success. I'll try again tomorrow.

@olegstepura
Copy link

@evilebottnawi, @michael-ciniawsky please let me know if you will answer anything to my sourcemap issue. If I should create a new separate issue, I will. If you think this is not anyhow related to postcss-loader, please tell me as well (but please let me know where should I create such an issue). Thanks!

@alexander-akait
Copy link
Member

@olegstepura yep, create new issue with repo and description problem, otherwise we can lose it here. Thanks!

@webpack-contrib webpack-contrib locked and limited conversation to collaborators May 19, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants