next.js中关于next.config.js配置的导出

因为我需要引入两个插件并导出
插件的官方例子分别为:

const withSass = require('@zeit/next-sass')
module.exports = withSass({
  cssModules: true,
  cssLoaderOptions: {
    importLoaders: 1,
    localIdentName: "[local]___[hash:base64:5]",
    sourceMap: true,
    modules: true,
  }
})

另一个

const withImages = require('next-images')
module.exports = withImages()

然后我不知道怎么把这个两个合并在一起### 问题描述

问题出现的环境背景及自己尝试过哪些方法

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

你期待的结果是什么?实际看到的错误信息又是什么?

阅读 6.4k
2 个回答

一句话,将plugin函数组合调用并暴露

你可以打印一下next.config.js中的withTypescript()和withScss函数(或者直接查看github withTypescript源码)。


这是打印widthSass的结果

const cssLoaderConfig = require('@zeit/next-css/css-loader-config')

module.exports = (nextConfig = {}) => {
  return 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,
        postcssLoaderOptions,
        sassLoaderOptions = {}
      } = nextConfig

      options.defaultLoaders.sass = cssLoaderConfig(config, {
        extensions: ['scss', 'sass'],
        cssModules,
        cssLoaderOptions,
        postcssLoaderOptions,
        dev,
        isServer,
        loaders: [
          {
            loader: 'sass-loader',
            options: sassLoaderOptions
          }
        ]
      })

      config.module.rules.push(
        {
          test: /\.scss$/,
          use: options.defaultLoaders.sass
        },
        {
          test: /\.sass$/,
          use: options.defaultLoaders.sass
        }
      )

      if (typeof nextConfig.webpack === 'function') {
        return nextConfig.webpack(config, options)
      }

      return config
    }
  })
}

注意关键的一行

if (typeof nextConfig.webpack === 'function') {
    return nextConfig.webpack(config, options)
}

解释一下,

  1. withSass/withTypescript/with-*函数都是接受nextConfig参数,nextConfig可配置项自己查看文档。函数返回一个配置对象,大概是{cssModule:true, webpack:() => {console.log('配置sass-loader/rules等')}}
  2. withSass/withTypescript/with-*函数执行后返回的webpack函数中有关键的一行,上文提到的,nextConfig中也可包含其他的webpack函数,并且也会执行
  3. 如果要混合使用,直接简单的包含就可以

withTypescript函数执行后返回对象

{  pageExtension: ['js', 'jsx', 'ts', 'tsx'],
   webpack: () => {console.log('typescript使用babel转义配置...')} 
}

返回的对象再传入withSass函数作为参数,合并配置过程中检测到typeof nextConfig.webpack === 'function',执行withTypescript的webpack函数

所以答案:

const withTypescript = require('@zeit/next-typescript')();
const withSass = require('@zeit/next-sass')();

module.exports = () => withSass(withTypescript ())
新手上路,请多包涵

楼主,问题解决了吗,我也遇到相同问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题