ReactJS - including other scss files in main.scss
Asked Answered
S

4

6

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));
  });
}
Scifi answered 3/9, 2017 at 20:18 Comment(3)
can you add the error you get and the import statement pleaseOrian
stackoverflow.com/users/2315280/bennygenel - updated my questionScifi
You will need to transpile your sever code before running it. You will need a client webpack config and a server webpack config.Angloirish
A
5

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.

Angloirish answered 5/9, 2017 at 23:28 Comment(3)
updated my webpack file and also index.js (starting point of react app ) - this is a server side rendering app - with the above code - I see Unexpected token, expected ( (1:8) > 1 | @import 'component';Scifi
@Scifi I see. You will need to transpile your server code before running it if you want to import your scss via web pack. github.com/realseanp/isomorphic-redux-react-webpack-starter There is an example of how to do itAngloirish
By transpile your server code I mean you will need to use webpack to bundle your server code and your client code.Angloirish
R
3

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.

Ripley answered 5/9, 2017 at 23:35 Comment(0)
D
3

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";
Domiciliary answered 6/9, 2017 at 0:7 Comment(0)
D
2

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

Dysart answered 6/9, 2017 at 12:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.