Arjenovic Arjenovic - 1 month ago 19
Sass (Sass) Question

Building both CSS and Javascript files with Webpack 1

I am trying to output both a css as a js bundle file within my webpack.config file but I am facing two issues:

1) My output file has a .js extension but one of the output files needs to be a css file (scss.bundle.css). How would I make this work?

2) My loaders needs to be linked to the correct output file, and I don't think that is properly working right now.

Please let me know if you are able to help me here. There is quite limited knowledge on webpack I think.

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
context: "", // directory we currently in
devtool: debug ? "inline-sourcemap" : null,
entry: {
client: "./js/client.js",
scss: "./css/compactview.scss"
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].bundle.js' // when out putting we create this kind of file
},
module: {
loaders: [
{
test: /\.js?$/, //anything thats a JS file gets run through babel-loader
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015'],
plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy']
}
},
{
test: /\.scss$/, // any scss files
loaders: ['style', 'css', 'sass'],
include:
}
]
},
watch: true, //automatically watch files when running webpack
plugins: debug ? [] : [ //if in debug mode, no plugins - if in production ..
new webpack.optimize.HotModuleReplacementPlugin(),
new webpack.optimize.DedupePlugin(), //strip out duplicate code
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), //gets rid of sourcemaps, comments, etc
],
};

Answer

Use the ExtractTextPlugin to pull the css out of the bundle and into a separate css file.

let ExtractTextPlugin = require('extract-text-webpack-plugin');

// multiple extract instances
let extractCSS = new ExtractTextPlugin('stylesheets/[name].css');
let extractLESS = new ExtractTextPlugin('stylesheets/[name].less');

module.exports = {
  ...
  module: {
    loaders: [
      {test: /\.scss$/i, loader: extractCSS.extract(['css','sass'])},
      {test: /\.less$/i, loader: extractLESS.extract(['css','less'])},
      ...
    ]
  },
  plugins: [
    extractCSS,
    extractLESS
  ]
};

Note that the webpack 2 plugin is different.