VINET VINET - 3 years ago 279
React JSX Question

How to add sass to webpack + react?

How correctly to add sass(in jsx import 'style.sass') in a config webpack + react?

var path = require('path');

var BUILD_DIR = path.resolve(__dirname, './');
var APP_DIR = path.resolve(__dirname, 'src/');

var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
devServer: {
contentBase: BUILD_DIR
},
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel-loader'
}
]
,
rules: [{
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
}]
}
};

module.exports = config;


Error:


ERROR in ./src/index.jsx Module parse failed:
C:\Users\steko\Desktop\TEST\m-react\src\index.jsx Unexpected token
(9:8) You may need an appropriate loader to handle this file type. |
render () { | return ( | | Hello React Project!!! |


git

Answer Source

In your modules section in webpack do this

module: {
    rules: [
        {
            test: /\.jsx?/,
            loader: 'babel-loader',
            include: APP_DIR
        },
        {
            test: /\.scss$/,
            use: ExtractTextPlugin.extract({
                fallback: "style-loader",
                use: "css-loader!sass-loader",
            })
        }
    ]
}

Then in your plugins area in your webpack code do this

plugins: [
    new ExtractTextPlugin('style.css'),
]

You will need this package extract-text-webpack-plugin

Please do let me know if you still have any issues.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download