import resolve from "./resolve"

exports.onCreateWebpackConfig = (
  { actions, stage, rules, plugins, loaders },
  { cssLoaderOptions = {}, postCssPlugins, useResolveUrlLoader, ...sassOptions }
) => {
  const { setWebpackConfig } = actions
  const PRODUCTION = stage !== `develop`
  const isSSR = stage.includes(`html`)

  const sassLoader = {
    loader: resolve(`sass-loader`),
    options: {
      sourceMap: useResolveUrlLoader ? true : !PRODUCTION,
      ...sassOptions,
    },
  }

  const sassRule = {
    test: /\.s(a|c)ss$/,
    use: isSSR
      ? [loaders.null()]
      : [
          loaders.miniCssExtract(),
          loaders.css({ ...cssLoaderOptions, importLoaders: 2 }),
          loaders.postcss({ plugins: postCssPlugins }),
          sassLoader,
        ],
  }
  if (useResolveUrlLoader && !isSSR) {
    sassRule.use.splice(-1, 0, {
      loader: `resolve-url-loader`,
      options: useResolveUrlLoader.options ? useResolveUrlLoader.options : {},
    })
  }
  const sassRuleModules = {
    test: /\.module\.s(a|c)ss$/,
    use: [
      !isSSR && loaders.miniCssExtract({ hmr: false }),
      loaders.css({ ...cssLoaderOptions, modules: true, importLoaders: 2 }),
      loaders.postcss({ plugins: postCssPlugins }),
      sassLoader,
    ].filter(Boolean),
  }

  let configRules = []

  switch (stage) {
    case `develop`:
    case `build-javascript`:
    case `build-html`:
    case `develop-html`:
      configRules = configRules.concat([
        {
          oneOf: [sassRuleModules, sassRule],
        },
      ])
      break
  }

  setWebpackConfig({
    module: {
      rules: configRules,
    },
  })
}

@@ -777,206 +777,8 @@
   %7D%0A
-  if (useResolveUrlLoader && !isSSR) %7B%0A    sassRule.use.splice(-1, 0, %7B%0A      loader: %60resolve-url-loader%60,%0A      options: useResolveUrlLoader.options ? useResolveUrlLoader.options : %7B%7D,%0A    %7D)%0A  %7D%0A
   co
@@ -797,24 +797,24 @@
 Modules = %7B%0A
+
     test: /%5C
@@ -1044,24 +1044,24 @@
 sassLoader,%0A
-
     %5D.filter
@@ -1070,24 +1070,384 @@
 oolean),%0A  %7D
+%0A  if (useResolveUrlLoader && !isSSR) %7B%0A    sassRule.use.splice(-1, 0, %7B%0A      loader: %60resolve-url-loader%60,%0A      options: useResolveUrlLoader.options ? useResolveUrlLoader.options : %7B%7D,%0A    %7D)%0A    sassRuleModules.use.splice(-1, 0, %7B%0A      loader: %60resolve-url-loader%60,%0A      options: useResolveUrlLoader.options ? useResolveUrlLoader.options : %7B%7D,%0A    %7D)%0A  %7D
 %0A%0A  let conf

Enable url() resolution for modules (#16451)