Skip to content

Instantly share code, notes, and snippets.

@smashercosmo
Last active April 22, 2016 12:21
Show Gist options
  • Save smashercosmo/49fccb524dc7c33608af to your computer and use it in GitHub Desktop.
Save smashercosmo/49fccb524dc7c33608af to your computer and use it in GitHub Desktop.
css-modules on server
'use strict';
const path = require('path');
const sassAndScssLoader = indentedSyntax => (
(source, filename) => require('node-sass').renderSync({
file: filename,
indentedSyntax
}).css
);
const lessLoader = source => {
let css = '';
const cb = (err, res) => {css = res.css};
require('less').render(source, {sync: true}, cb);
return css;
};
const loaders = {
scss: sassAndScssLoader(false),
sass: sassAndScssLoader(true),
less: lessLoader,
styl: (source, filename) => require('stylus')(source).set('filename', filename).render(),
css: source => source
};
module.exports = {
extensions: ['.scss', '.sass', '.styl', '.less'],
generateScopedName: process.env.NODE_ENV !== 'production' ? '[name]__[local]' : '[hash:base64:5]',
preprocessCss: function (css, filename) {
const ext = path.extname(filename).substr(1);
return loaders[ext](css, filename);
}
};
const cssModulesConfig = require('./cssModulesConfig');
require('babel-register');
require('css-modules-require-hook')(cssModulesConfig);
require('./main'); // <-- This is your main server file
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import autoprefixer from 'autoprefixer';
const loaders = {
'css': '',
'less': '!less-loader',
'scss': '!sass-loader',
'sass': '!sass-loader?indentedSyntax',
'styl': '!stylus-loader'
};
export default function makeConfig(isDevelopment) {
function stylesLoaders() {
return Object.keys(loaders).map(ext => {
const prefix = `css-loader?modules&importLoaders=1&localIdentName=${isDevelopment ? '[name]__[local]' : '[hash:base64:5]'}`
const extLoaders = prefix + loaders[ext];
const loader = isDevelopment
? `style-loader!${extLoaders}`
: ExtractTextPlugin.extract('style-loader', extLoaders);
return {
loader: loader,
test: new RegExp(`\\.(${ext})$`)
};
});
}
return {
/* your webpack configuration */
module: {
loaders: [/* your loaders */].concat(stylesLoaders())
},
postcss: () => [autoprefixer({browsers: 'last 2 version'})],
plugins: [
// render styles into separate cacheable file to prevent FOUC and
// optimize for critical rendering path.
new ExtractTextPlugin('app-[hash].css', {
allChunks: true
})
// your plugins here
]
/* your webpack configuration */
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment