Skip to content

Instantly share code, notes, and snippets.

@blech75
Created August 16, 2018 14:42
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save blech75/b9238c5569e03a637c9cd21d596e80f0 to your computer and use it in GitHub Desktop.
next.js webpack config for outputting AMP-specific Sass to separate file
// Copied from @zeit/next-sass and modified to so that we can define AMP styles
// in *.amp.scss and normal styles in *.scss (excludes *.amp.scss). Normal
// styles are output as before; AMP styles are output to styles-amp.scss
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const cssLoaderConfig = require('@zeit/next-css/css-loader-config');
const commonsChunkConfig = require('@zeit/next-css/commons-chunk-config');
module.exports = (nextConfig = {}) =>
Object.assign({}, nextConfig, {
webpack: (config, options) => {
if (!options.defaultLoaders) {
throw new Error(
'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade'
);
}
const { dev, isServer } = options;
const {
cssModules,
cssLoaderOptions,
sassLoaderOptions = {}
} = nextConfig;
// pass the same instance of ExtractTextPlugins to all css related modules
// so that they compile to the same file in production
let { extractCSSPlugin, extractCSSPluginAMP } = options;
if (!extractCSSPlugin) {
extractCSSPlugin = new ExtractTextPlugin('static/styles.css');
extractCSSPluginAMP = new ExtractTextPlugin('static/styles-amp.css');
config.plugins.push(extractCSSPlugin);
config.plugins.push(extractCSSPluginAMP);
options.extractCSSPlugin = extractCSSPlugin;
options.extractCSSPluginAMP = extractCSSPluginAMP;
if (!isServer) {
// modify config.plugins -- specifically CommonsChunkPlugin.minChunks
// for all sass files
config = commonsChunkConfig(config, /\.(scss|sass)$/);
}
}
const loaderConfigOpts = {
cssModules,
cssLoaderOptions,
dev,
isServer,
loaders: [
{
loader: 'sass-loader',
options: sassLoaderOptions
}
]
};
// add CSS config to webpack. (server gets ignore-loader)
options.defaultLoaders.sass = cssLoaderConfig(
config,
extractCSSPlugin,
loaderConfigOpts
);
options.defaultLoaders.sassAMP = cssLoaderConfig(
config,
extractCSSPluginAMP,
loaderConfigOpts
);
config.module.rules.push(
{
// negative lookbehind to specify everything but AMP SASS
test: /(?<!\.amp)\.s[ca]ss$/,
use: options.defaultLoaders.sass
},
{
// only AMP SASS files
test: /\.amp\.s[ca]ss$/,
use: options.defaultLoaders.sassAMP
}
);
if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options);
}
return config;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment