webpack-contrib / sass-loader

Compiles Sass to CSS
MIT License
3.9k stars 427 forks source link

SassError: expected "{". #867

Closed laihuamin closed 4 years ago

laihuamin commented 4 years ago

image

use: sass-loader css-loader style-loader

package.json:

{ "css-loader": "^3.6.0", "sass": "^1.26.10", "sass-loader": "^9.0.2", "style-loader": "^1.2.1" }

alexander-akait commented 4 years ago

It looks like you just deleted our lovely crafted issue template. It was there for good reasons. Please help us solving your issue by answering the questions asked in this template. I'm closing this. Please either update the issue with the template and reopen, or open a new issue.

robjtede commented 4 years ago

I belive this is a legitimate issue and one without a work-around.

See my investigation on the ngx-markdown issue tracker. https://github.com/jfcere/ngx-markdown/issues/252#issuecomment-664542938

In my case, it surfaced with useages of sass modules being completely rejected after an upgrade of packages to support Angular v10, one of which started depending on node-sass.

@evilebottnawi I can open another issue if you want the full issue template filled out.

alexander-akait commented 4 years ago

@robjtede You have invalid configuration css-loader twice applied

robjtede commented 4 years ago

If that's the underlying problem with this issue then my case is different. There's definitely not two instances of css-loader.

ERROR in .../libs/.../src/index.scss (
     .../node_modules/css-loader/dist/cjs.js??ref--14-1
    !.../node_modules/postcss-loader/src??embedded
    !.../node_modules/resolve-url-loader??ref--14-3
    !.../node_modules/sass-loader/dist/cjs.js??ref--14-4
    !.../libs/.../src/index.scss
)

Module build failed (from .../node_modules/sass-loader/dist/cjs.js):
SassError: Invalid CSS after "  @include badge": expected "}", was ".load-host;"
        on line 4 of libs/.../src/lib/badge/badge.scss
        from line 1 of .../libs/.../src/index.scss
>>   @include badge.load-host;
alexander-akait commented 4 years ago

SassError: Invalid CSS after " @include badge": expected "}", was ".load-host;"

It is sass error, we can't fix problems with your code, sorry

robjtede commented 4 years ago

This is valid sass, supported by dart-sass as described in the comment I linked. I see this is not the right place to discuss the issue, sorry for the bother.

alexander-akait commented 4 years ago

@robjtede node-sass and dart-sass have incompatibility with some syntaxes

robjtede commented 4 years ago

I understand, but the fact is that if node-sass appears in the dependency tree, it is preferred over dart-sass. The error is thrown because node-sass is being used and doesn't support sass modules.

Created a minimal reproduction repo: https://github.com/robjtede/repro-sass-loading

alexander-akait commented 4 years ago

No, we prefer sass (dart-sass) https://github.com/webpack-contrib/sass-loader/blob/master/src/utils.js#L13

alexander-akait commented 4 years ago

If you have problem with angular-cli, please open an issue in angular-cli repo

robjtede commented 4 years ago

Thanks for linking to that code. Now that's understood, I've went to look for similar lines in angular cli: https://github.com/angular/angular-cli/blob/378faa70119a193cff6a4407f70f0229bb88456f/packages/angular_devkit/build_angular/src/angular-cli-files/models/webpack-configs/styles.ts#L118. I believe this is the culprit. Thanks for your help.

alexander-akait commented 4 years ago

Yep, problem on angular-cli side

zhangyuyard commented 3 years ago
            {
                test: /\.s(a|c)ss$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'sass-loader'
                ],
            },
            {
                test: /\.(jpe?g|gif|png|svg)$/,
                loader: 'url-loader',
                options: {
                    limit: 8 * 1024,
                    name: "[hash:10].[ext]",
                }
            },
            {
                exclude: /\.(s?(a?|c)ss|js|html)$/,
                loader: 'file-loader',
                options: {
                    name: '[hash:10].[ext]'
                }
            }

exculde "css" or "scss" at file-loader

and its worked for me

file-loader 、css-loader was conflicted perhaps

saidsoualhi commented 3 years ago

@planAplan are you using storybook with Angular ? I've tried your solution but it's not working for me here is my main.js file:

module.exports = {
    webpackFinal: async (config, { configType }) => {
    config.module.rules.push(
      {
        test: /\.s(a|c)ss$/,
        use: ['style-loader', 'sass-loader', 'css-loader']
      },
      {
        test: /\.(jpe?g|gif|png|svg)$/,
        loader: 'url-loader',
        options: {
          limit: 8 * 1024,
          name: '[hash:10].[ext]'
        }
      },
      {
        exclude: /\.(s?(a?|c)ss|js|html)$/,
        loader: 'file-loader',
        options: {
          name: '[hash:10].[ext]'
        }
      }
    );

    // Return the altered config
    return config;
    },
    stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
    addons: ['@storybook/addon-links', '@storybook/addon-essentials']
};

and my preview.js file:

import { setCompodocJson } from '@storybook/addon-docs/angular';
import docJson from '../documentation.json';
import '@angular/localize/init';
setCompodocJson(docJson);

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' }
};
zhangyuyard commented 3 years ago

@planAplan are you using storybook with Angular ? I've tried your solution but it's not working for me here is my main.js file:

module.exports = {
    webpackFinal: async (config, { configType }) => {
    config.module.rules.push(
      {
        test: /\.s(a|c)ss$/,
        use: ['style-loader', 'sass-loader', 'css-loader']
      },
      {
        test: /\.(jpe?g|gif|png|svg)$/,
        loader: 'url-loader',
        options: {
          limit: 8 * 1024,
          name: '[hash:10].[ext]'
        }
      },
      {
        exclude: /\.(s?(a?|c)ss|js|html)$/,
        loader: 'file-loader',
        options: {
          name: '[hash:10].[ext]'
        }
      }
    );

    // Return the altered config
    return config;
    },
    stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
    addons: ['@storybook/addon-links', '@storybook/addon-essentials']
};

and my preview.js file:

import { setCompodocJson } from '@storybook/addon-docs/angular';
import docJson from '../documentation.json';
import '@angular/localize/init';
setCompodocJson(docJson);

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' }
};

i`ve never used storybook with Angular but Maybe it's a problem with the order of loader parsing. You can try this

{
  test: /\.s(a|c)ss$/,
  use: ['style-loader', 'css-loader', 'sass-loader' ]
}

I hope it helps you 🙏

dkniffin commented 3 years ago

If anyone lands here from webpacker 6 / rails, your issue might be that you are including css-loader in your custom webpacker configs. It is included already by webpacker, I believe.

Edit: I actually ended up opting out of the webpacker scss config entirely by adding this into base.js:

const scssConfigIndex = webpackConfig.module.rules.findIndex((config) => ".scss".match(config.test))
webpackConfig.module.rules.splice(scssConfigIndex, 1)
SGoldenGraham commented 3 years ago

Not sure why this has been closed? There is no solution to the issue. I am also running into this.

OsmarJoseph commented 3 years ago

Apparently I have fixed this by just setting this order to my style loaders, as the documentation

image
FilipGrebowski commented 2 years ago

Apparently I have fixed this by just setting this order to my style loaders, as the documentation image

Yes - the order is a priority when dealing with loaders. :) I'd consider this an answer to the question.

andriiradkevych commented 2 years ago

I've had same problem , first of all I've updated storybook webpack version to 5 , then I replaced styles ryles which was used by storybook webpack config , to rules , I use in my webpack config , belowe you can see my .storybook/main.js file

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

const rules = require('../webpack/rules');

module.exports = {
  stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/preset-scss',
  ],
  core: {
    builder: 'webpack5',
  },
  webpackFinal: async (config) => {
    config.resolve.modules = [
      ...(config.resolve.modules || []),
      path.resolve(__dirname, '../src/client'),
    ];

    config.module.rules.push(rules.css());

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

    const newRules = config.module.rules.filter(
      (entity) =>
        ![/\.css$/, /\.s[ca]ss$/].some(
          (regExp) => regExp.toString() === entity.test.toString()
        )
    );

    return {
      ...config,
      module: {
        ...config.module,
        rules: newRules,
      },
    };
  },
};

webpack/rules.js

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

const css = () => {
  return {
    test: /\.scss$/,
    use: [
      MiniCssExtractPlugin.loader,
      {
        loader: 'css-loader',
        options: {
          modules: true,
        },
      },
      {
        loader: 'sass-loader',
      },
    ],
  };
};
agounane commented 2 years ago

i had the same error, i added .scss to the css file on my laravel webpack.mix.js

mix.sass('resources/ui/frontend/css/frontend.scss', 'public/assets/frontend/css');

weili520 commented 2 years ago

I am using webpack5, and encounter the same problem, the error caused by the false module's rules, as follows:

截屏2022-02-20 14 47 22

The regular expression for css files should be /\.css/i, haha.

snowinmars commented 2 years ago

I got this error, when I apply loaders to the same files twice.

// webpack.config.js with error
{
//...
  module: {
    rules: [
      {
        test: /\.(scss|css)$/,
        use: ...
      },
      {
        test: /\.module\.(scss|css)$/,
        use: ...
      },
    ]
  }
}
// webpack.config.js without error
{
//...
  module: {
    rules: [
      {
        oneOf: [ // <---
          {
            test: /\.(scss|css)$/,
            use: ...
          },
          {
            test: /\.module\.(scss|css)$/,
            use: ...
          },
        ]
      }
    ]
  }
}
taw1313 commented 2 years ago

I finally got storybook 6.5.9 and react 18.x to work. I had to use a combination of most of the suggestions above...

Below is my .storybook/main.js

const path = require('path');

const alias = {
  'my-kit': path.resolve(__dirname, '../src'),
};

module.exports = {
  stories: [
    './stories/**/*.stories.mdx',
    './stories/**/*.stories.@(js|jsx|ts|tsx)',
  ],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    '@storybook/preset-create-react-app',
  ],
  framework: '@storybook/react',
  core: {
    builder: '@storybook/builder-webpack5',
  },
  webpackFinal: async (config) => {
    const scssConfigIndex = config.module.rules.findIndex((c) =>
      '.scss'.match(c.test),
    );
    if (scssConfigIndex > 0 && config.module.rules[scssConfigIndex]?.oneOf)
      config.module.rules[scssConfigIndex].oneOf.push({
        test: /\.(css|s(a|c)ss)$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
        include: path.resolve(__dirname, '../'),
      });
    else
      config.module.rules.push({
        test: /\.(css|s(a|c)ss)$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
        include: path.resolve(__dirname, '../'),
      });
    return {
      ...config,
      resolve: { ...config.resolve, alias },
    };
  },
};

I need to do some more work on the logic... But in my case I had to add the "loaders" into the oneOf rules that contained scss rules. Thank you @snowinmars for your work above.

alonsofer198 commented 1 year ago

ERROR Failed to compile with 1 error 12:40:40

error in ./src/assets/style.scss

Syntax Error: SassError: expected "}". ╷ 301 │ } │ ^ ╵ src/assets/style.scss 301:2 root stylesheet

@ ./src/assets/style.scss 4:14-225 15:3-20:5 16:22-233 @ ./src/main.js @ multi (webpack)-dev-server/client?http://192.168.0.28:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

rogergerecke commented 1 year ago

I had the same problem in my case, I create style.scss file with windows power shell. And it's creating the file under the wrong UTF-16 encoding. After many time of searching i see it in my wonderfull PhpStorm on the bottom this wrong encoding. One cklick to chang it. In UTF-8 its work holy shi... :-)

worthy7 commented 9 months ago

My file was UTF-8 with BOM, I converted to standard UTF-8 and it worked.

ahmedakhtar11 commented 6 months ago

This simply means you're missing brackets, because old scss/sass runs without brackets.

Instead of

body font-family: $font color: $white

do better syntax with brackets after declaration of a class or element:

body{ font-family: $font; color: $white; }

cw-shwetasaindane commented 1 week ago

Module build failed (from ./node_modules/react-scripts/node_modules/sass-loader/dist/cjs.js): SassError: expected "{". ╷ 2 │ module.exports = {"rightArrow":"_3IdQ"}; │ ^

My main.js const path = require('path'); const MiniCssExtractPlugin = require('cw-mini-css-extract-plugin');

module.exports = { stories: ['../packages/stories/*/.story.@(js|mdx|jsx)'], // Adjust as needed addons: [ '@storybook/preset-create-react-app', '@storybook/addon-onboarding', '@storybook/addon-links', '@storybook/addon-essentials', '@chromatic-com/storybook', '@storybook/addon-interactions', ], framework: { name: '@storybook/react-webpack5', options: {}, }, staticDirs: ['./public'], // Adjust static directory path core: { builder: 'webpack5', }, webpackFinal: async (config, { mode }) => { config.module.rules.push( // JavaScript and JSX files { test: /.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env', '@babel/preset-react'], }, }, }, // Handle regular SCSS files (not modules) { test: /.s?css$/, exclude: /.module.scss$/, sideEffects: true, use: ['style-loader', 'css-loader', 'sass-loader'], include: [path.resolve(dirname, '../packages/core/src/')], }, // Handle SCSS modules { test: /.module.scss$/, sideEffects: true, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', options: { modules: { mode: 'local', localIdentName: '[hash:base64:4]', }, sourceMap: false, }, }, 'sass-loader', ], include: [ path.resolve(dirname, '../node_modules/@oxygen/core/src/'), path.resolve(__dirname, '../node_modules/@oxygen/theme/scss/'), ], }, // Handle images { test: /.(png|jpg|gif|svg)$/, use: ['file-loader'], } );

// Add MiniCssExtractPlugin for CSS handling
config.plugins.push(
  new MiniCssExtractPlugin({
    filename: 'css/[name].css',
    chunkFilename: 'css/[id].css',
    ignoreOrder: false,
  })
);

// Resolve .js and .jsx extensions
config.resolve.extensions.push('.js', '.jsx');

// Setup theme and extensions based on environment variables
let extensions = [];
let cssThemeFilePath = '';

if (process.env.STORYBOOK_THEME === 'mobility') {
  extensions = [
    '.mobility.js',
    '.mjs',
    '.js',
    '.jsx',
    '.json',
    '.mobility.module.scss',
    '.module.scss',
  ];
  cssThemeFilePath = '../node_modules/@oxygen/theme/scss/_mobility-theme.scss';
} else if (process.env.STORYBOOK_THEME === 'cartrade') {
  extensions = [
    '.cartrade.js',
    '.mjs',
    '.js',
    '.jsx',
    '.json',
    '.cartrade.module.scss',
    '.module.scss',
  ];
  cssThemeFilePath = '../node_modules/@oxygen/theme/scss/_cartrade-theme.scss';
} else {
  // Default to oxygen theme
  extensions = [
    '.oxygen.js',
    '.mjs',
    '.js',
    '.jsx',
    '.json',
    '.oxygen.module.scss',
    '.module.scss',
  ];
  cssThemeFilePath = '../node_modules/@oxygen/theme/scss/_oxygen-theme.scss';
}

config.resolve.alias['@oxygen/theme/utils$'] = path.resolve(__dirname, cssThemeFilePath);
config.resolve.extensions = extensions;

return config;

}, };

"sass": "^1.78.0", "sass-loader": "^10.2.0", "css-loader": "^3.6.0", "style-loader": "^0.21.0", "webpack": "^5.94.0"