ReactJS - including other scss files in main.scss

5.5k views Asked by At

In my reactJS application - I am including all .scss files in one main.scss file - under styles folder in src folder. I have the following webpack configuration. tried including main.scss file directly in my main component - getting error at '@import' where I import other scss files. if i include separate scss file styles are fine - but how to get this working with one main.scss file and how to include it?

error: Unexpected token, expected ( (1:8)

1 | @import 'mycomponent';

module.exports = {
  entry: [
    'webpack-hot-middleware/client',
    path.resolve(__dirname, 'src'),
  ],
  output: {
    path: path.resolve(__dirname, 'src'),
    filename: 'bundle.js',
    publicPath: '/',
  },
  plugins: [
    new ExtractTextPlugin('bundle.css', { allChunks: true }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development'),
        WEBPACK: true,
      },
    }),
  ],
  module: {

    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          query: {
            presets: ['react-hmre'],
          },
        },
        include: path.resolve(__dirname, 'src'),
      },
     {
    use: ExtractTextPlugin.extract({
      fallback: "style-loader",
      use: [
         'css-loader', 
         'sass-loader?outputStyle=expanded'.
      ]
    }),
    test: /\.scss$/,
    exclude: /node_modules/
  }
    ],
  },
};

index.js

import React from 'react';
import { render } from 'react-dom';
import { createBrowserHistory } from 'history';
import { ConnectedRouter, routerMiddleware } from 'react-router-redux';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from './components/homepage';
import reducers from './reducers';
import '../styles/main.scss';


const history = createBrowserHistory();
const store = createStore(reducers, applyMiddleware(routerMiddleware(history)));

render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>
  , document.getElementById('app'));

if (process.env.NODE_ENV === 'development' && module.hot) {
  module.hot.accept();
  module.hot.accept('./reducers', () => {
    const nextRootReducer = require('./reducers').default; // eslint-disable-line global-require
    store.replaceReducer(nextRootReducer(store.asyncReducers));
  });
}
4

There are 4 answers

3
pizzarob On

You should import your .scss file via javascript in your top level React component.

import './styles/main.scss';

Webpack will then include it in your bundle.

For production you will want to use the Extract Text Plugin for webpack which will export a separate css file from the import statement.

0
inostia On

Webpack operates on .js files. You need to convert your .scss into a .css file using the ExtractTextPlugin:

{test: /\.scss$/,
    use: ExtractTextPlugin.extract({
        fallback: "style-loader",
        use: [{
            loader: "css-loader" // translates CSS into CommonJS
        }, {
            loader: "sass-loader"
        }]
    })
}

Set your webpack entry point for this to the directory in which yourmain.scss file lives, then create an index.js in that directory with the following line:

require("./main.scss") (or import ./main.scss)

The path you include here: <link rel="stylesheet" type="text/css" href="./styles/main.scss"> should be the path to the generated .css file.

0
Noby Fujioka On

Below settings work for me.

webpack.config.js

{
    use: ExtractTextPlugin.extract({
      fallback: "style-loader",
      use: [
         'css-loader', //knows how to deal with css
         'autoprefixer-loader?browsers=last 3 versions',
         'sass-loader?outputStyle=expanded' //this one is applied first.
      ]
    }),
    test: /\.scss$/,
    exclude: /node_modules/
  }

in the top index.js

import "./styles/main.scss";
import "./reactApp";

example of main.scss

// Import any of your custom variables for bootstrap here first.
@import "my-theme/custom";
// Then, import bootstrap scss
@import "~bootstrap/scss/bootstrap";  
//for bootstrap 3 using bootstrap-sass
$icon-font-path: '~bootstrap-sass/assets/fonts/bootstrap/';
@import '~bootstrap-sass/assets/stylesheets/_bootstrap.scss';
// Finally import any custom styles.
@import "my-theme/master-theme";
0
andy wilson On

I would just import them the way you are doing and dont reuse id or class names unless you want the styles to be the same so:

import '../styles/main1.scss';
import '../styles/main2.scss';
....

Like that and so on