Skip to content

Instantly share code, notes, and snippets.

@Grsmto
Created June 15, 2018 08:39
Show Gist options
  • Save Grsmto/8e7ade37862f1c8b4d019da8dd423450 to your computer and use it in GitHub Desktop.
Save Grsmto/8e7ade37862f1c8b4d019da8dd423450 to your computer and use it in GitHub Desktop.
Next.js support for css-modules & normal css at the same time, same behaviour as CRA
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const cssLoaderConfig = require('@zeit/next-css/css-loader-config');
const commonsChunkConfig = (config, test = /\.css$/) => {
config.plugins = config.plugins.map(plugin => {
if (
plugin.constructor.name === 'CommonsChunkPlugin' &&
// disable filenameTemplate checks here because they never match
// (plugin.filenameTemplate === 'commons.js' ||
// plugin.filenameTemplate === 'main.js')
// do check for minChunks though, because this has to (should?) exist
plugin.minChunks != null
) {
const defaultMinChunks = plugin.minChunks;
plugin.minChunks = (module, count) => {
if (module.resource && module.resource.match(test)) {
return true;
}
return defaultMinChunks(module, count);
};
}
return plugin;
});
return config;
};
module.exports = {
webpack: (config, options) => {
const { dev, isServer } = options;
extractCSSPlugin = new ExtractTextPlugin({
filename: 'static/style.css'
});
config.plugins.push(extractCSSPlugin);
options.extractCSSPlugin = extractCSSPlugin;
if (!isServer) {
config = commonsChunkConfig(config);
}
options.defaultLoaders.css = cssLoaderConfig(
config,
options.extractCSSPlugin,
{}
);
config.module.rules.push(
{
test: /\.css$/,
exclude: /\.module\.css$/,
use: options.defaultLoaders.css
},
{
test: /\.module\.css$/,
use: cssLoaderConfig(config, extractCSSPlugin, {
cssModules: true,
dev,
isServer
})
}
);
config = commonsChunkConfig(config, /\.(module\.css|css)$/);
return config;
}
};
@yeou
Copy link

yeou commented Oct 12, 2018

How would this work for NextJs 7? They use mini-css-extract-plugin there.

@nhayhoc
Copy link

nhayhoc commented Jan 5, 2019

How would this work for NextJs 7? They use mini-css-extract-plugin there.

I have the same problem

@richardblondet
Copy link

Same here

@samuelg0rd0n
Copy link

Using next.js 8.1... not working :-( Any help?

@wallynm
Copy link

wallynm commented Feb 26, 2020

Need help with this :/

@wallynm
Copy link

wallynm commented Feb 27, 2020

Guys, just found this issue inside NextJS:
vercel/next-plugins#149

And also, @webdeb created this package:
https://github.com/webdeb/next-styles

Just installed and worked flawless - using NextJS version 9.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment