Unable to import sass files in react

Viewed 2860

I'm using the following boilerplate : https://github.com/spravo/typescript-react-express

I designed a first component : Button

import * as React from 'react';

import './button.scss';

export interface IButton {
  value: string;
  onClick: () => void;
}

class Button extends React.Component<IButton, {}> {
  public render () {
    return (
      <div className='Button'>
        <button onClick={this.props.onClick} className='Button__btn'>
          {this.props.value}
        </button>
      </div>
    );
  }
}

export default Button;

And in the button.scss I have this simple line :

.Button {
  background-color: red;
}

But I get the following error :

(function (exports, require, module, __filename, __dirname) { .Button {

SyntaxError: Unexpected token .

This is my webpack config (quite the same as the one from the repo) except the config.common.js for the webpack migration :

'use strict';

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

const config = require('../config')(process.env.NODE_ENV);
const vendors = require('./vendor');

const NODE_ENV = process.env.NODE_ENV || 'development';

module.exports = function getConfig(dirname) {
  return {
    target: 'web',
    context: path.resolve(dirname),
    stats: {
      chunks: false,
      colors: true,
    },
    entry: {
      vendor: vendors
    },
    resolve: {
      extensions: [ '.ts', '.tsx', '.js', '.scss', '.css' ],
      modules: [
        path.resolve(__dirname, '..', 'src'),
        path.resolve(__dirname, '..', 'node_modules'),

      ]
    },
    output: {
      path: config.PUBLIC_FOLDER,
      filename: '[name].[hash].js',
      chunkFilename: '[name].[chunkhash].js',
      publicPath: config.PUBLIC_PATH
    },
    module: {
      rules: []
    },
    optimization:{
      splitChunks:{
        name: 'vendor'
      }
    },
    plugins: [
      new webpack.NoEmitOnErrorsPlugin(),
      // new webpack.optimize.CommonsChunkPlugin({
      //   name: 'vendor'
      // }),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(NODE_ENV)
        },
        __CLIENT__: true,
        __SERVER__: false,
        __DEV__: NODE_ENV === 'development',
        __TEST__: false
      })
    ]
  };
};

The Css loaders :

'use strict';

const isDevelopment = (process.env.NODE_ENV || 'development') === 'development';
const autoprefixer = require('autoprefixer');


module.exports = {
  scssLoader: [
    {
      loader: 'css-loader',
      options: {
        minimize: !isDevelopment,
        sourceMap: isDevelopment
      }
    },
    {
      loader: 'postcss-loader',
      options: {
        sourceMap: isDevelopment,
        plugins: [
          autoprefixer({
            browsers:['ie >= 8', 'last 4 version']
          })
        ]
      }
    },
    {
      loader: 'sass-loader',
      options: {
        sourceMap: isDevelopment  
      }
    }
  ]
};

It seems that the only scss that works is in the styles/index.scss but I don't get why it doesn't take other scss files.

My tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "baseUrl" : "./src",
    "target": "es5",
    "jsx": "react",
    "alwaysStrict": true,
    "sourceMap": true,
    "outDir": "dist",
    "lib": [
      "dom",
      "es2015",
      "es5",
      "es6"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "typings"
  ],
  "exclude": [
    "node_modules"
  ]
}
1 Answers

It is really weird that your webpack config "module.rules" is an empty array! That is where your loader settings should be added.

If I were you, I would have copied the content of css-loaders config file and pasted in your webpack.config.js file. Make sure you store it in a normal variable/object instead of module.exports.

This is how my webpack config looks like:

const styleLoader = {
  test: /\.(scss)$/,
  include: path.resolve(__dirname, 'src'),
  use: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: [
      {
        loader: 'css-loader',
        options: {
          sourceMap: true,
          minimize: true
        }
      }, {
        loader: 'postcss-loader',
        options: {
          sourceMap: true,
          config: {
            path: path.join(__dirname, 'postcss.config.js')
          }
        }
      }, {
        loader: 'sass-loader',
        options: { sourceMap: true }
      }
    ]
  })
};

And then my webpack config looks like below. Pay attention to the modules.rules section:

module.exports = {
  entry: {
    app: ['babel-polyfill', 'whatwg-fetch', srcPath('index.js')],
    silentrenew: [srcPath('silentrenew.js')]
  },
  output: {
    path: path.resolve(__dirname, 'build'),
    publicPath: '/',
    filename: '[name].js'
  },
  devtool: 'source-map',
  plugins: [
    htmlPlugin('index.html', 'app'),
    new ExtractTextPlugin('bundle.css'),
  ],
  module: {
    rules: [
      babelLoader,
      fontLoader,
      svgLoader,
      styleLoader
    ]
  }
};
Related