Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Last active August 12, 2020 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieMason/776d5735bb6300bb825f09b202e3cdd0 to your computer and use it in GitHub Desktop.
Save JamieMason/776d5735bb6300bb825f09b202e3cdd0 to your computer and use it in GitHub Desktop.
next.config.js helpers

next.config.js Helpers

Mutate next.js internal config to make changes which are not officially available to you. Be sure to know what you're doing.

Helpers

const getPluginsByConstructorName = (constructorName, plugins) =>
  plugins.filter((plugin) => plugin.constructor.name === constructorName);

const getRulesByLoaderName = (loaderName, allRules) => {
  const matches = [];

  const visit = (rules) =>
    rules.forEach((rule) => {
      if (Array.isArray(rule.use)) {
        visit(rule.use);
      }
      if (Array.isArray(rule.oneOf)) {
        visit(rule.oneOf);
      }
      if (typeof rule.loader === 'string' && rule.loader.includes(loaderName)) {
        matches.push(rule);
      }
    });

  visit(allRules);
  return matches;
};

Example Usage

// next.config.js
module.exports = () => {
  return {
    webpack(config, options) {
      getRulesByLoaderName('mini-css-extract-plugin', config.module.rules).forEach((use) => {
        use.options.filename = 'static/css/[name]-[hash].css';
      });

      getPluginsByConstructorName('NextMiniCssExtractPlugin', config.plugins).forEach((plugin) => {
        plugin.options.filename = 'static/css/[name]-[hash].css';
      });

      return config;
    },
  };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment