Skip to content

webpack2 options are useless #128

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
shjyh opened this issue Oct 29, 2016 · 30 comments
Closed

webpack2 options are useless #128

shjyh opened this issue Oct 29, 2016 · 30 comments

Comments

@shjyh
Copy link

shjyh commented Oct 29, 2016

I use postcss-loader in webpack 2.x config with options just like the sample in document.

I received a warn when I run it :

PostCSS Config could not be loaded. Please check your PostCSS Config

then I create postcss.config.js file in the root of my project folder. it seems everything ok.

but the warn shows again when i import a set of common UI style out of my project.

is necessary put the postcss.config.js file in the common parent folder of all stylesheet files ?

and I want to import this common UI style into different project with different postcss config, how can I do?

@ai
Copy link
Contributor

ai commented Oct 29, 2016

postcss.config.js should be in project root.

Could you show your webpack config when you try to put PostCSS plugins there?

@shjyh
Copy link
Author

shjyh commented Oct 29, 2016

here's my webpack.config.js

const path = require('path');
const webpack = require('webpack');
const Md5HashPlugin = require('webpack-md5-hash');

const autoprefixer = require('autoprefixer');

function getPostcssPlugins(){
    return [
        autoprefixer({
            cascade : false,
            browser : ['Chrome >= 49', 'Firefox >= 49', 'Edge >= 13']
        })
    ]
}

const {DEBUG,readJson,commonPath,webpackPlugins:{StatsWritterPlugin}} = require('../helper');

const babelrc = readJson(path.resolve(__dirname,'./.babelrc'));
const publicPath = '/resource/';

const vendor = ['vue','vue-router'];

module.exports = function (name){

    const config = {
        plugins:[
        ]
    };

    switch(name){
        case 'vendor':
            config.entry = {vendor};
            config.output={
                path : path.resolve(__dirname, './web/resource'),
                filename : DEBUG?'[name].hash.js':'[name].[chunkhash].js',
                library:'[name]_[chunkhash]',
                publicPath
            };
            config.plugins.push(new webpack.DllPlugin({
                path:'./.manifest/vendor.manifest.json',
                name:'[name]_[chunkhash]',
                context:__dirname
            }));
            config.plugins.push(new StatsWritterPlugin(path.resolve(__dirname,'./.manifest/vendor.stats.json'),{
                source:false,
                modules:false,
                children:false,
                chunks:false
            }));
            break;
        default:
            config.entry = {app:'./resource/app.entry.js'};
            config.output={
                path:path.resolve(__dirname,'./web/resource'),
                filename:DEBUG?'app.hash.js':'app.[chunkhash].js',
                publicPath
            };
            config.module={
                rules : [
                    {
                        test : /\.js$/,
                        include:[path.resolve(__dirname,'./resource'),commonPath],
                        loader : 'babel-loader',
                    },
                    {
                        test : /\.scss$/,
                        use : [
                            'style-loader',
                            `css-loader${DEBUG ? '' : '?minimize'}`,
                            {
                                loader : 'postcss-loader',
                                options : {
                                    plugins:getPostcssPlugins
                                }
                            },
                            'sass-loader'
                        ]
                    },
                    {
                        test : /\.(png|jpg|svg)$/,
                        loader : 'file-loader',
                        options : {
                            name : 'assets/[hash].[ext]',
                            publicPath
                        }
                    },
                    {
                        test : /\.vue$/,
                        loader : 'vue-loader',
                        options : {
                            postcss : getPostcssPlugins(),
                            loaders : {
                                js : 'babel-loader',
                                sass: `style-loader!css-loader${DEBUG?'':'?minimize'}!sass-loader`
                            }
                        }
                    }
                ]
            };
            config.resolve={
                extensions:['.js','.json','.vue'],
                alias:{
                    common:commonPath
                }
            };
            if(babelrc) config.module.rules[0].options = babelrc;

            config.plugins.push(new webpack.DefinePlugin({
                DEBUG
            }));
            config.plugins.push(new webpack.DllReferencePlugin({
                context:__dirname,
                manifest:require('./.manifest/vendor.manifest.json')
            }));

            if(DEBUG){
                config.watch = true;
                config.watchOptions = {
                    aggregateTimeout : 500,
                    ignored : /node_modules/
                };
                config.devtool = 'inline-source-map';
            }
            config.plugins.push(new StatsWritterPlugin(path.resolve(__dirname,'./.manifest/app.stats.json'),{
                source:false,
                modules:false,
                children:false,
                chunks:false
            }));
            break;
    }


    if (!DEBUG){
        config.plugins.push(new webpack.optimize.UglifyJsPlugin({
            compress : { warnings : false },
            output : { comments : false },
            sourceMap : false
        }));
        config.plugins.push(
            new webpack.DefinePlugin({
                'process.env' : {
                    NODE_ENV : '"production"'
                }
            })
        );
        config.plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
        config.plugins.push(new webpack.optimize.DedupePlugin());
    }

    config.plugins.push(new Md5HashPlugin());

    return config;
};

@ai
Copy link
Contributor

ai commented Oct 29, 2016

Strange. Could you comment vue-loader, to be sure, that error came from postcss-loader?

@marcelaraujo
Copy link

@ai postcss.config.js is a requirement now? Because I got that issue too and I had to use LoaderOptionsPlugin to solve it (http://pastebin.com/Lmka3rju).

When I did this http://pastebin.com/0J9dcXCp, it did not work as I expected. After a while debugging, I found that

module.exports = function (source, map) {
    if ( this.cacheable ) this.cacheable();

    var loader = this;
    var file   = loader.resourcePath;
    var params = loaderUtils.parseQuery(loader.query);

    var options  = params.plugins || loader.options.postcss;

    // can not read `postcss` of undefined

@ai
Copy link
Contributor

ai commented Oct 29, 2016

@marcelaraujo could you show webpack config without LoaderOptionsPlugin?

You don’t need LoaderOptionsPlugin. We recommend to use postcss.config.js, but it is not requirement.

@marcelaraujo
Copy link

marcelaraujo commented Oct 29, 2016

@ai

const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
const precss = require('precss');
const mqpacker = require('css-mqpacker');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: [
    'react-hot-loader/patch',
    'babel-polyfill',
    'whatwg-fetch',
    'webpack-dev-server/client?http://localhost:3000',
    'webpack/hot/only-dev-server',
    './src/index',
  ],
  output: {
    path: path.resolve(process.cwd(), 'dist'),
    publicPath: '/',
    filename: 'app.[hash].js',
  },
  devtool: 'eval',
  module: {
    rules: [{
      test: /\.js$/,
      include: [
        path.resolve(process.cwd(), 'src'),
      ],
      use: [{
        loader: 'babel-loader',
        options: {
          presets: [['es2015', { modules: false }], 'stage-0', 'react'],
          plugins: ['transform-runtime', 'transform-object-rest-spread', 'react-hot-loader/babel'],
        },
      }],
    }, {
      test: /\.css$/,
      include: [
        path.resolve(process.cwd(), 'src'),
      ],
      use: [{
        loader: 'style-loader',
      }, {
        loader: 'css-loader',
        options: {
          modules: true,
          importLoaders: true,
          localIdentName: '[hash:base64:5]',
        },
      }],
    }, {
      test: /\.css$/,
      include: [
        path.resolve(process.cwd(), 'node_modules'),
      ],
      use: [{
        loader: 'style-loader',
      }, {
        loader: 'css-loader',
        options: {
          autoprefixer: false,
        },
      }, {
        loader: 'postcss-loader',
        options: {
          postcss: [
            precss(),
            autoprefixer({
              browsers: [
                'last 3 version',
                'ie >= 10',
              ],
            }),
            mqpacker(),
          ],
        },
      }],
    }, {
      test: /\.(jpe?g|png|gif|svg)$/,
      use: [{
        loader: 'file-loader',
      }, {
        loader: 'image-webpack',
        options: {
          progressive: true,
          optimizationLevel: 7,
          interlaced: false,
          pngquant: {
            quality: '65-90',
            speed: 4,
          },
        },
      }],
    }],
  },
  plugins: [
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    // new webpack.ProgressPlugin(),
    new HtmlWebpackPlugin({
      hash: false,
      template: './index.html',
    }),
    // new webpack.LoaderOptionsPlugin({
    //   test: /\.css$/,
    //   debug: true,
    //   options: {
    //     postcss: [
    //       precss(),
    //       autoprefixer({
    //         browsers: [
    //           'last 3 version',
    //           'ie >= 10',
    //         ],
    //       }),
    //       mqpacker(),
    //     ],
    //     context: path.join(__dirname, 'src'),
    //     output: {
    //       path: path.join(__dirname, 'dist'),
    //     },
    //   },
    // }),
  ],
};

and the Webpack output

PostCSS Config could not be loaded. Please check your PostCSS Config.

[./node_modules/css-loader/index.js?{"autoprefixer":false}!./node_modules/postcss-loader/index.js?{"postcss":[{"version":"5.2.5","plugins":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"postcssPlugin":"precss","postcssVersion":"5.2.5"},null,null]}!./node_modules/sanitize.css/sanitize.css] ./~/css-loader?{"autoprefixer":false}!./~/postcss-loader?{"postcss":[{"version":"5.2.5","plugins":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"postcssPlugin":"precss","postcssVersion":"5.2.5"},null,null]}!./~/sanitize.css/sanitize.css 10.7 kB {0} [built]
 [./node_modules/css-loader/index.js?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/components/NavigationBar/styles.css] ./~/css-loader?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/components/NavigationBar/styles.css 531 bytes {0} [built]
 [./node_modules/css-loader/index.js?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/containers/App/style.css] ./~/css-loader?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/containers/App/style.css 856 bytes {0} [built]
 [./node_modules/css-loader/index.js?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/containers/Dashboard/style.css] ./~/css-loader?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/containers/Dashboard/style.css 359 bytes {0} [built]
 [./node_modules/css-loader/index.js?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/containers/Setup/style.css] ./~/css-loader?{"modules":true,"importLoaders":true,"localIdentName":"[hash:base64:5]"}!./src/containers/Setup/style.css 401 bytes {0} [built]

@ai
Copy link
Contributor

ai commented Oct 29, 2016

@marcelaraujo what do you have at params and loader.query on this line https://github.com/postcss/postcss-loader/blob/master/index.js#L46 ?

@marcelaraujo
Copy link

{ postcss:
   [ { version: '5.2.5',
       plugins: [Object],
       postcssPlugin: 'precss',
       postcssVersion: '5.2.5' },
     null,
     null ] }
PostCSS Config could not be loaded. Please check your PostCSS Config.

my package.json

{
  "name": "app",
  "version": "1.0.0",
  "scripts": {
    "start": "node ./webpack/webpack.server.js",
    "build": "rimraf ./dist && webpack --config ./webpack/webpack.prod.config.js",
    "preview": "http-server ./dist -p 3001 -c-1",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "babel-runtime": "^6.18.0",
    "immutable": "^3.8.1",
    "react": "^15.3.2",
    "react-dom": "^15.3.2",
    "react-redux": "^4.4.5",
    "react-router": "^4.0.0-alpha.4",
    "react-router-redux": "^4.0.6",
    "redux": "^3.6.0",
    "redux-immutable": "^3.0.8",
    "redux-saga": "^0.12.0",
    "reselect": "^2.5.4",
    "sanitize.css": "^4.1.0",
    "whatwg-fetch": "^1.0.0"
  },
  "devDependencies": {
    "auto-prefixer": "^0.4.2",
    "autoprefixer": "^6.5.1",
    "babel-core": "^6.18.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-transform-object-rest-spread": "^6.16.0",
    "babel-plugin-transform-react-constant-elements": "^6.9.1",
    "babel-plugin-transform-react-inline-elements": "^6.8.0",
    "babel-plugin-transform-runtime": "^6.15.0",
    "babel-polyfill": "^6.16.0",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-0": "^6.16.0",
    "css-loader": "^0.25.0",
    "css-mqpacker": "^5.0.1",
    "eslint": "^3.9.0",
    "eslint-config-airbnb": "^12.0.0",
    "eslint-plugin-import": "^2.0.1",
    "eslint-plugin-jsx-a11y": "^2.2.3",
    "eslint-plugin-react": "^6.4.1",
    "extract-text-webpack-plugin": "^2.0.0-beta.4",
    "html-webpack-plugin": "^2.22.0",
    "http-server": "^0.9.0",
    "image-webpack-loader": "^3.0.0",
    "postcss-loader": "^1.1.0",
    "precss": "^1.4.0",
    "react-hot-loader": "^3.0.0-beta.6",
    "react-router-loader": "^0.5.4",
    "redux-logger": "^2.7.2",
    "rimraf": "^2.5.4",
    "style-loader": "^0.13.1",
    "webpack": "^2.1.0-beta.25",
    "webpack-dev-server": "^2.1.0-beta.9",
    "webpack-module-hot-accept": "^1.0.4"
  }
}

@marcelaraujo
Copy link

marcelaraujo commented Oct 29, 2016

Output for line https://github.com/postcss/postcss-loader/blob/master/index.js#L63

{ plugins: [],
  options:
   { cwd: '/Users/marcelaraujo/WebstormProjects/webapp-admin',
     env: undefined,
     webpack:
      { version: 2,
        emitWarning: [Function: emitWarning],
        emitError: [Function: emitError],
        exec: [Function: exec],
        resolve: [Function: resolve],
        resolveSync: [Function: resolveSync],
        options: [Object],
        webpack: true,
        sourceMap: false,
        emitFile: [Function: bound ],
        _module: [Object],
        _compilation: [Object],
        _compiler: [Object],
        fs: [Object],
        target: 'web'
        ....

@ai
Copy link
Contributor

ai commented Oct 29, 2016

Strange, could you create some small test project? I will look on next week.

@marcelaraujo
Copy link

Yeap. I'll send to you later ;)

@gaastonsr
Copy link

gaastonsr commented Oct 30, 2016

Loading plugins through webpack 2 is not working at the moment. Check this comment for reference.

@tleunen
Copy link

tleunen commented Nov 1, 2016

I'm experiencing the same issue

what do you have at params and loader.query on this line https://github.com/postcss/postcss-loader/blob/master/index.js#L46 ?

loader.query is empty and params is {}.

Here's my config:

{
    loader: 'postcss',
    options: {
        plugins: () => [autoprefixer]
    }
}

@ai
Copy link
Contributor

ai commented Nov 1, 2016

Seems like query works in some cases and didn't work in other (on same versions).

Right now just use PostCSS common config. Anyway it is recommended way

@BerndWessels
Copy link

Same issue here, I tried multiple things, but nothing seemed to work.

          {
            loader: 'postcss-loader',
            options: {
              plugins: [
                autoprefixer({
                  browsers: [
                    'last 3 version',
                    'ie >= 10',
                  ],
                })
              ]
            }
          },

@ai
Copy link
Contributor

ai commented Nov 2, 2016

Until webpack 2 is not released I will promote only common config 8c7cede

Have no idea how to fix this problems (webpack has really problems with complexity)

@ai ai closed this as completed Nov 2, 2016
@flying-sheep
Copy link

the issue is webpack/webpack#3136

@Imanullah
Copy link

if you are using webpack 2

in plugin webpack config add this

    new webpack.LoaderOptionsPlugin({
        options: {
            postcss: [
                autoprefixer({
                    browsers: ['last 2 version']
                })
            ]
        }
    })

@ai
Copy link
Contributor

ai commented Nov 11, 2016

@Imanullah don’t use LoaderOptionsPlugin. Just check current postcss-loader docs. Use PostCSS common config.

@cebor
Copy link

cebor commented Dec 16, 2016

@ai whats wrong with LoaderOptionsPlugin? Does it not work the same?

imjared added a commit to imjared/react-starter that referenced this issue Jan 8, 2017
@kmiyashiro
Copy link

I am getting this problem and webpack 2 has been released.

@michael-ciniawsky
Copy link
Member

@kmiyashiro Please post your webpack.config.js / postcss.config.js (if)

@kmiyashiro
Copy link

kmiyashiro commented Feb 19, 2017

webpack.config.babel.js
// bable.js extension tells babel-register to process this with babel

const path = require('path');
const webpack = require('webpack');

const merge = require('webpack-merge');
const HtmlPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// npm script
const SEGMENT_KEY = process.env.BEER_SEGMENT_KEY;
const TARGET = process.env.npm_lifecycle_event;
const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build'),
};
const commonHtmlConfig = {
  title: 'Beer Feels',
  appMountId: 'root',
  mobile: true,
  template: 'templates/index.html',
  inject: false,
  segmentKey: SEGMENT_KEY,
};

const common = {
  entry: {
    app: PATHS.app,
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    modules: [
      PATHS.app,
      'node_modules',
    ],
    alias: {
      beerfeels: PATHS.app,
    },
  },
  output: {
    path: PATHS.build,
    filename: 'app.js',
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader',
        ],
        include: PATHS.app,
      },
      {
        test: /\.jsx?$/,
        use: 'babel-loader',
        include: PATHS.app,
      },
    ],
  },
  plugins: [
    new webpack.EnvironmentPlugin([
      'BEER_FEELS_API_URL',
    ]),
  ],
};

if (TARGET === 'start' || !TARGET) {
  module.exports = merge.smart(common, {
    output: {
      publicPath: 'http://localhost:8080/',
    },
    // https://webpack.github.io/docs/webpack-dev-server.html
    devServer: {
      contentBase: PATHS.build,
      historyApiFallback: true,
      hot: true,
      inline: true,

      stats: 'errors-only',
      host: process.env.HOST,
      port: process.env.PORT,
    },
    module: {
      rules: [
        {
          test: /\.scss$/,
          use: [
            'style-loader',
            'css-loader',
            {
              loader: 'postcss-loader',
              options: {
                plugins() {
                  return [
                    require('autoprefixer')({
                      browsers: ['last 2 versions'],
                      remove: false,
                    }),
                  ];
                },
              },
            },
            {
              loader: 'sass-loader',
              options: {
                includePaths: ['node_modules'],
              },
            },
          ],
          include: PATHS.app,
        },
      ],
    },
    // devtool: 'eval-source-map',
    plugins: [
      new HtmlPlugin(Object.assign({
        cache: true,
      }, commonHtmlConfig)),
      new webpack.HotModuleReplacementPlugin(),
    ],
  });
}

if (TARGET === 'build') {
  module.exports = merge.smart(common, {
    module: {
      rules: [
        {
          test: /\.scss$/,
          use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
              'style-loader',
              'css-loader',
              {
                loader: 'postcss-loader',
                options: {
                  plugins() {
                    return [
                      require('autoprefixer')({
                        browsers: ['last 2 versions'],
                        remove: false,
                      }),
                    ];
                  },
                },
              },
              {
                loader: 'sass-loader',
                options: {
                  includePaths: ['node_modules'],
                },
              },
            ],
          }),
          include: PATHS.app,
        },
      ],
    },

    plugins: [
      new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
      }),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('production'),
        },
      }),
      new HtmlPlugin(Object.assign({
        hash: true,
      }, commonHtmlConfig)),
      new ExtractTextPlugin('style/main.css'),
    ],
  });
}

@michael-ciniawsky
Copy link
Member

michael-ciniawsky commented Feb 19, 2017

@kmiyashiro

// In General
- 'css-loader'
+ { loader: 'css-loader', options: { importLoaders: 1 } } // .css
+ { loader: 'css-loader', options: { importLoaders: 2 } } // .scss

// In Build/Production
if (TARGET === 'build') {
  module.exports = merge.smart(common, {
    module: {
      rules: [
        {
          test: /\.scss$/,
          use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
            // you don't want the logic for adding <style></style> in your CSS bundle :D
-              'style-loader',
              'css-loader',
              {

Otherwise I can't see any obvious errors in your webpack.config.js, despite UgilfyJSPlugin as the first in webpack.config.plugins. Be aware that any ES2015 Syntax may also break with UglifyJS[Plugin] atm, another more modern option would be babel-preset-babili 😛 .Also HTMLWebpackPlugin { inject: false } doesn't inject the bundles, but I guess that's on propose 🙃 . Can you give my the error logs please (message && stacktrace) in case it still doesn't work?

@kmiyashiro
Copy link

@michael-ciniawsky thanks! It may have been the style-loader that was causing the issue? I removed it and added the importLoaders options to the css-loaders and it works now. Thanks!

@michael-ciniawsky
Copy link
Member

@kmiyashiro Yep, likely to be the cause of your problem 🙃

@zhengjunxiang
Copy link

zhengjunxiang commented Mar 6, 2017

@shjyh Hello, you can try this:

const Webpack = require('webpack');
const Autoprefixer = require('autoprefixer');

new Webpack.LoaderOptionsPlugin({ options: { postcss: [ Autoprefixer({
    browsers: ['Chrome >= 49', 'Firefox >= 49', 'Edge >= 11', 'ie >= 9']
  }) ] } })

It's out of use postcss.config.js .
I added it to the plugins options and it works now. Thanks!

@shjyh
Copy link
Author

shjyh commented Mar 6, 2017

great, and now i use postcss.config.js to config my options

@mythz
Copy link

mythz commented May 8, 2017

I'm getting the same error with the latest version of postcss-loader whilst configuring it in postcss options in LoaderOptionsPlugin.

The error is resolved by putting an empty postcss.config.js file in my project's root but it's absurd I need to pollute my source folder with empty config files, so I just reverted back to:

"postcss-loader": "^1.3.3",

instead, which doesn't have this issue.

@michael-ciniawsky
Copy link
Member

michael-ciniawsky commented May 8, 2017

Please try the fix branch and provide feedback 😛 npm i -D postcss/postcss-loader#fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests