Skip to content
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

Error compiling .scss file #69

Closed
chandu opened this issue Mar 26, 2015 · 42 comments
Closed

Error compiling .scss file #69

chandu opened this issue Mar 26, 2015 · 42 comments

Comments

@chandu
Copy link

chandu commented Mar 26, 2015

I am trying to compile .scss files using this loader.
I am getting the error below when I invoke webpack command:

Hash: 471ab211129c4252e031
Version: webpack 1.7.3
Time: 52ms
    + 1 hidden modules

ERROR in ./dummy.scss
Module parse failed: /home/chandu/www/sass-loader-test/node_modules/sass-loader/index.js!/home/chandu/www/sass-loader-test/dummy.scss Line 1: Unexpected token {
You may need an appropriate loader to handle this file type.
| body {
|   background-color: #fff; }
| 

I have created a repo to replicate the issue: https://github.com/Chandu/sass-loader-test

When I use node-sass directly I don't get any error. You can try this running node test.js from the repo linked above.

chandu@nobuntu:~/www/sass-loader-test$ node test.js 
body {
  background-color: #fff; }

Am pretty sure I am doing something wrong, but not sure what it is.
Can anyone help me with this?

@chandu
Copy link
Author

chandu commented Mar 26, 2015

I added a css-loader to the pipeline and the issue is now resolved.

@chandu chandu closed this as completed Mar 26, 2015
@danazkari
Copy link

hey @chandu I have the same issue right now and I do have installed the css-loader installed and it's in the pipeline.

webpack.config.js

    loaders: [
        {
            test: /\.scss$/,
            loader: 'style!css!sass'
        }
    ]

index.scss

body, html {
    margin: 0;
    padding: 0;
    font-family: 'Helvetica', 'Arial', sans-serif;
    color: #666;
}

What did you do different?

@danazkari
Copy link

nm, I just fixed it, was missing the module object inside the webpack.config.js. Thanks!

@seanwash
Copy link

@danazkari Strange, I'm having the same issue as well and I do have the module object like so:

var BrowserSyncPlugin = require('browser-sync-webpack-plugin'),
    ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: './source/index.coffee',

  output: {
    filename: './app/bundle.js'
  },

  module: {
    loaders: [
      {test: /\.coffee$/, loader: 'coffee'},
      {test: /\.scss$/, loader: ExtractTextPlugin.extract('css!sass'), include: './source/scss'}
    ]
  },

  plugins: [
    new BrowserSyncPlugin({
      host: 'localhost',
      port: 9000,
      server: {baseDir: ['./app']}
    }),

    new ExtractTextPlugin('./app/bundle.css', {
      allChunks: true
    })
  ]
}
body {
  background: red;
  color: #fff;
}

@raphaelparent
Copy link

I have the same problem here.
@seanwash Did you manage to make it work?

This works on the client though. But every time I refresh, there's a glitch before css is loaded because webpack is building the file, which is not exactly what I want.

const config = {
    devtool: "source-map",
    entry: [
        `webpack-dev-server/client?http://${host}:${port}`,
        "webpack/hot/only-dev-server",
        "./src/client.js"
    ],
    output: {
        filename: "bundle.js",
        chunkFilename: "[name].bundle.js",
        path: dist,
        publicPath: `http://${host}:${port}/dist/`
    },
    module: {
    loaders: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loaders: ["react-hot", "babel?cacheDirectory"]
            },
            {
                test: /\.scss$/,
                loaders: ["style", "css", "sass"]
            },
            {
                test: /\.(jpe?g|png|gif|svg)$/,
                loader: "file"
            }
        ]
    },
    sassLoader: {
        includePaths: [path.resolve(__dirname, "../style")]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            "process.env": {
                NODE_ENV: JSON.stringify("development"),
                BROWSER: JSON.stringify(true)
            }
        }),
        new WebpackErrorNotificationPlugin()
    ]
};

And I try to import it like that.

import '../../style/utils/normalize.scss';

And I get that error.

SyntaxError: /Users/rparent/Documents/CTSProjects/arsenal/cms/application/app/style/utils/normalize.scss: Unexpected token (9:5)
   7 |  */
   8 | 
>  9 | html {
     |      ^
  10 |   font-family: sans-serif; /* 1 */
  11 |   -ms-text-size-adjust: 100%; /* 2 */
  12 |   -webkit-text-size-adjust: 100%; /* 2 */

@rpmonteiro
Copy link

Would be great if you guys could post a solution once you found it 👍

@raphaelparent
Copy link

I managed to make it work with the ExtractTextPlugin. It makes a big bundle of all required stylesheet (I think) and then makes it available for the server-side rendering.

Might not be the best way but it definitely work.

@seanwash
Copy link

seanwash commented Apr 8, 2016

@raphaelparent wow I don't know how I missed your reply! Sorry about that.

I also solved this problem with the extract text plugin, then I require the css file at the top of of main is file. I can post the code if anyone needs.

@rpmonteiro
Copy link

@seanwash Yes, please do show the code!! :)

I fixed the error on the first post by adding !css to require('css!./stylesheets/main.scss');
Took me about 4h to figure this out.. phew.

It compiles just fine to JS, but I still don't have the CSS file.
So I'm trying to setup the ExtractTextPlugin, and I've come across this:

ERROR in ./~/css-loader!./src/stylesheets/main.scss Module build failed: CssSyntaxError: /css-loader!/Users/...

Any ideas guys?

@isaac-peka
Copy link

Experiencing the same problem, not exactly sure what the problem is but it looks like the scss file is being treated like a javascript module even though there are loaders in place.

SyntaxError: /Users/sampeka/dev/sharestyle/app/styles/components/Logo.scss: Unexpected token (1:0)
> 1 | .logo img {
    | ^
  2 |    width: 100%;
  3 | }
  4 | 
    at Parser.pp.raise (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:1378:13)
    at Parser.pp.unexpected (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:2817:8)
    at Parser.pp.parseExprAtom (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:749:12)
    at Parser.parseExprAtom (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:4305:22)
    at Parser.pp.parseExprSubscripts (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:504:19)
    at Parser.pp.parseMaybeUnary (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:484:19)
    at Parser.pp.parseExprOps (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:415:19)
    at Parser.pp.parseMaybeConditional (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:397:19)
    at Parser.pp.parseMaybeAssign (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:360:19)
    at Parser.pp.parseExpression (/Users/sampeka/dev/sharestyle/node_modules/babylon/index.js:324:19)

@fxlemire
Copy link

I had the same issue, and somehow... I insist on "somehow", I fixed it by changing my loader from loader: 'style!css!sass' to loaders: ["style", "css", "sass"].

And here comes the mesmerizing part: I changed it back to loader: 'style!css!sass' and it still worked... somehow...

@ilearnio
Copy link

ilearnio commented Apr 19, 2016

Had the same issue, it turned out that it was Node who was throwing error but not Webpack since I'm running my code on both server and client. And Node, of course, doesn't know what to do with .scss files

So I fixed it by putting this code into my server-only file

require.extensions['.scss'] = function () {}

@erik-sn
Copy link

erik-sn commented May 19, 2016

I'm not sure if everyone above was in the same situation, but I ran across this issue trying to do Isomorphic/Server Side rendering for React.

@ilearnio's solution didn't work for me - however the problem is definitely Node. Basically the wrinkle is that Webpack does its magic by looking for require/imports. So you must require/import the .scss file - however if you are doing Isomorphic/Server Side rendering, Node does not know what these .scss or even .css files are and has no webpack to help it, and you end up with a lot of "Unexpected Token" errors.

I followed the solution described here: and it worked well. Basically you declare the process.env.BROWSER variable in webpack, and conditionally require your .scss files on the client side if this variable exists. You also delete it at the beginning of your server.js file so it does not exist - so the server side code will not try to import it.

@vanekbr
Copy link

vanekbr commented Aug 30, 2016

I had the same problem, and for me solution was pretty simple. Webpack using different conf file for tests and there was no loaders for css|scss files. Hope it helps somebody.

@ivanminutillo
Copy link

why. no one. shows. a solution with code. -_-

@bigopon
Copy link

bigopon commented Sep 3, 2016

This is what works for my .less

module: {
    loaders: [
        {
            test: /\.(less|css)$/,
            include: /resources/,
            loaders: [
                'style?singleton',
                ExtractTextPlugin.extract(`css?${JSON.stringify({
                    // sourceMap: DEBUG,
                    // CSS Modules https://github.com/css-modules/css-modules
                    // modules: true,
                    // camelCase: true,
                    // localIdentName: DEBUG ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
                    // CSS Nano http://cssnano.co/options/
                    minimize: !DEBUG,
                    calc: false,
                })}`),
                'postcss',
                'less',
            ]
        },
    ]
},
plugins: [
    new ExtractTextPlugin('style.min.css'),
]

Note

I use webpack@2.1.0-beta.21 and extract-text-webpack-plugin@2.0.0-beta.4

@msuzoagu
Copy link

msuzoagu commented Sep 12, 2016

HI! I am having a bit of a problem getting sass-loader working properly. Current structure of project (as it relates to sass configuration):

  - projectdir/
    - src/ 
       - app.js (root component, which imports styles in stylesheets/main.scss) 
   - stylesheets/
      - base/ 
      - components/
      - vendors/
      - main.scss

webpack.config.dev.js

  {
     // Load SCSS 
      test: /\.scss$/,  
     loaders: ['style', 'css', 'sass'],  
     // tell webpack where to look for sass/css files?  
     include:path.resolve(__dirname, 'stylesheets')  
  }

now in stylesheets/main.scss, I have the following:

  // each component makes use of what it needs 
  .landingPage-nav-component {
    @import 'base/all';
    @import 'vendors/all';
    @import 'components/header';
  }

When I run npm start I expect the styles in stylesheets/main.scss to be available in app but rather I get the error:

  Error in ./stylesheets/main.scss
Module parse failed: /Users/comp1/Code/Javascript/React/nonAdmin_frontend/stylesheets/main.scss 
Unexpected token (14:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (14:0)
 @ ./src/app.js 17:0-35 

Chrome dev has this error message:

./stylesheets/main.scss
Module parse failed: /Users/comp1/Code/Javascript/React/nonAdmin_frontend/stylesheets/main.scss 
Unexpected character '@' (13:0)
You may need an appropriate loader to handle this file type. 

Any tips on what I might be doing wrong?

@LoicUV
Copy link

LoicUV commented Sep 13, 2016

@msuzoagu I'm in the exact same situation.

@Bosper
Copy link

Bosper commented Sep 13, 2016

Also I, Someone found solution?

@msuzoagu
Copy link

msuzoagu commented Sep 13, 2016

@LoicUV and @Bosper: commenting out:

 {
     include:path.resolve(__dirname, 'stylesheets')  
  }

got everything working. Not sure why but thought it might be helpful for you both to know.

@chellberg
Copy link

@fxlemire your solution somehow worked for me too. Thanks!

@toJanhonen
Copy link

as @msuzoagu stated, include and/or exclude statements break this loader. i do not understand why this issue is closed. what am i missing here?

being able to include and exclude certain files is vital in my setup, so the workaround of removing the statement(s) is not really doing it for me.
just to clarify, i would like to understand if this is a bug, or desired behaviour of this loader.

@toJanhonen
Copy link

never mind. was completely my bad.
include and exclude statements work as they should.

@mcntsh
Copy link

mcntsh commented Nov 4, 2016

I fixed this issue in webpack@2.1.0-beta.25 by passing a value for includePaths...

ExtractTextPlugin.extract({
   fallbackLoader: 'style-loader',
   loader: 'css-loader!sass-loader?includePaths[]=' + path.resolve(__dirname, './src')
})

@Natumsol
Copy link

Natumsol commented Dec 2, 2016

I have met the same problem, and it is caused by passing wrong params to ExtractTextPlugin:

module: {
        loaders: [{
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract("style-loader", "css-loader", "sass-loader")
        }]
}

and I have solved it by doing this:

module: {
        loaders: [{
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract("style-loader", "css!sass")
        }]
}

@alex3t
Copy link

alex3t commented Dec 28, 2016

This config fixed problem with include path for me:

			{
				test: /\.(scss|css)$/,
				include: [path.resolve(__dirname, 'src/components')],
				loader: ExtractTextPlugin.extract('style?singleton', [
					`css-loader?modules&importLoaders=1`,
					'postcss-loader',
					`sass-loader`
				].join('!'))
			},
			{
				test: /\.(scss|css)$/,
				exclude: [path.resolve(__dirname, 'src/components')],
				loader: ExtractTextPlugin.extract('style?singleton', [
					`css`,
					`postcss`,
					`sass`
				].join('!'))
			},

@jaimz22
Copy link

jaimz22 commented Jan 9, 2017

I just want to let you all know that I had this exact same problem. In my case it turns out that I had a typo. I had modules instead of module

double check ALL your keywords!

@andreyluiz
Copy link

@sampeka I have the exact same problem you had. Did you solve the problem?

@erikjohnsen6d
Copy link

I'm still not seeing a fix here that works for me.

@nrvarun
Copy link

nrvarun commented Jan 30, 2017

{ test: /\.scss$/, loader: ETP.extract("style-loader", "css!postcss!sass!") }

This worked for me and ETP is ExtractTextPlugin. The issue i had was that the file name was wrong. Silly issue 👍

@brettinternet
Copy link

brettinternet commented Jan 31, 2017

Explicitly excluding node_modules was the solution for me.

{
      test: /\.scss$/,
      exclude: /node_modules/,
      loaders: ['style-loader', 'css-loader', 'sass-loader'],
}

If you have to include node_modules for specific css files like Bootstrap or Toastr, then either @import the css files into your styles.scss or create a separate loader with them specifically for /\.css$/ files that includes node_modules.

@erikjohnsen6d
Copy link

Update: My issue was odd. It was actually a GitHub lost commit unrelated to the project, but with identical results.

@ghost
Copy link

ghost commented Feb 12, 2017

If someone like me still needing this information this is my webpack.config file @chandu gave the idea how to solve it. Thanks.
I'm using webpack 2.2 and extract-text-plugin@beta (^2.0.0-rc.3)
image

@andreyluiz
Copy link

@erik-sn solution solved for me. For the ones who are lazy and do not want to go to Stackoverflow, here follows.

Basically, just set in your webpack config for client side:

plugins: [
  new webpack.DefinePlugin({
    'process.env.BROWSER': JSON.stringify(true),
  })
],

Then, in the component that is being rendered on server side, just test:

if (process.env.BROWSER) {
  require('./MyStyle.scss');
}

Solved for me. Hope it helps. :)

@uoc1691
Copy link

uoc1691 commented Aug 4, 2017

Had the same issue. It was the path used for include. It was incorrect. Here's a working config.

image

@ParthBarot-BoTreeConsulting
Copy link

ParthBarot-BoTreeConsulting commented Sep 21, 2017

Setting up an existing codebase and facing the same issue, Tried everything but its not working.

node version - v8.0.0
webpack version - 1.15.0
sass-loader version - 3.2.3

Following is the webpack config snippet

const cssLoader = !config.compiler_css_modules
  ? 'css?sourceMap'
  : [
    'css?modules',
    'sourceMap',
    'importLoaders=1',
    // 'localIdentName=[name]__[local]___[hash:base64:5]',
    'localIdentName=[local]',
    'outputStyle=expanded'
    // includePaths[]= + encoreURIComponent(paths.base('app','styles')) ?
  ].join('&');

webpackConfig.module.loaders.push({
  test: /\.scss$/,
  include: /app/,
  loaders: [
    'style',
    cssLoader,
    'postcss',
    'sass'
  ]
});

webpackConfig.module.loaders.push({
  test: /\.css$/,
  include: /app/,
  loaders: [
    'style',
    cssLoader,
    'postcss'
  ]
});

// Don't treat global SCSS as modules
webpackConfig.module.loaders.push({
  test: /\.scss$/,
  exclude: /app/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss',
    'sass'
  ]
});

// Don't treat global, third-party CSS as modules
webpackConfig.module.loaders.push({
  test: /\.css$/,
  exclude: /app/,
  loaders: [
    'style',
    'css?sourceMap',
    'postcss'
  ]
});

webpackConfig.sassLoader = {
  includePaths: paths.client('styles'),
  outputStyle: 'expanded'
};

webpackConfig.postcss = [
  cssnano({
    sourcemap: true,
    autoprefixer: {
      add: true,
      remove: true,
      browsers: ['last 2 versions']
    },
    safe: true,
    discardComments: {
      removeAll: true
    }
  })
];

@shamspias
Copy link

npm install sass-loader node-sass webpack --save-dev

this will working fine.

@gyaneshgouraw
Copy link

gyaneshgouraw commented Sep 4, 2018

Any body visiting this page in 2018, this piece of code made it work for me.

     {
        test: /\.scss$/,
        use: sassExtractPlugin.extract({
          fallback: 'style-loader',
          use: [
            {
              loader: 'css-loader',
            },
            'sass-loader'
          ]
        }),
     }

@SiamakEshghi
Copy link

It works for me:
{
test: /.scss$/,
use: extractPlugin.extract({
use: ["css-loader", "sass-loader", "postcss-loader"],
fallback: 'style-loader'
})
}

@nicolasflorth
Copy link

@raphaelparent wow I don't know how I missed your reply! Sorry about that.

I also solved this problem with the extract text plugin, then I require the css file at the top of of main is file. I can post the code if anyone needs.

I am looking for your solution 2 years later. Why to bother to add it!? Important it was that you was able to fix it. Oh God

@Ashish567
Copy link

@raphaelparent wow I don't know how I missed your reply! Sorry about that.
I also solved this problem with the extract text plugin, then I require the css file at the top of of main is file. I can post the code if anyone needs.

I am looking for your solution 2 years later. Why to bother to add it!? Important it was that you was able to fix it. Oh God

@benmerchant
Copy link

never mind. was completely my bad.
include and exclude statements work as they should.

@toJanhonen I tried that fix (commenting out the include property, and now it works perfectly again.

Quick snippet
use: [MiniCssExtractPlugin.loader,'css-loader','sass-loader']
"webpack": "^4.29.6",
"mini-css-extract-plugin": "^0.5.0",
"css-loader": "^2.1.1",
"sass-loader": "^7.1.0",
"node-sass": "^4.11.0"

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