当前位置: 首页 > 文档资料 > Next.js 中文文档 >

自定义 webpack 配置

优质
小牛编辑
123浏览
2023-12-01

Examples
  • Custom webpack bundle analyzer

可以使用些一些常见的模块

  • @zeit/next-css
  • @zeit/next-sass
  • @zeit/next-less
  • @zeit/next-preact
  • @zeit/next-typescript

注意: webpack方法将被执行两次,一次在服务端一次在客户端。你可以用isServer属性区分客户端和服务端来配置

多配置可以组合在一起,如:

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

module.exports = withTypescript(withSass({
  webpack(config, options) {
    // Further custom configuration here
    return config
  }
}))

为了扩展webpack使用,可以在next.config.js定义函数。

// next.config.js is not transformed by Babel. So you can only use javascript features supported by your version of Node.js.

module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders }) => {
    // Perform customizations to webpack config
    // Important: return the modified config
    return config
  },
  webpackDevMiddleware: config => {
    // Perform customizations to webpack dev middleware config
    // Important: return the modified config
    return config
  }
}

webpack的第二个参数是个对象,你可以自定义配置它,对象属性如下所示:

  • buildId - 字符串类型,构建的唯一标示
  • dev - Boolean型,判断你是否在开发环境下
  • isServer - Boolean 型,为true使用在服务端, 为false使用在客户端.
  • defaultLoaders - 对象型 ,内部加载器, 你可以如下配置

    • babel - 对象型,配置babel-loader.
    • hotSelfAccept - 对象型, hot-self-accept-loader配置选项.这个加载器只能用于高阶案例。如 @zeit/next-typescript添加顶层 typescript 页面。

defaultLoaders.babel使用案例如下:

// Example next.config.js for adding a loader that depends on babel-loader
// This source was taken from the @zeit/next-mdx plugin source:
// https://github.com/zeit/next-plugins/blob/master/packages/next-mdx
module.exports = {
  webpack: (config, {}) => {
    config.module.rules.push({
      test: /.mdx/,
      use: [
        options.defaultLoaders.babel,
        {
          loader: '@mdx-js/loader',
          options: pluginOptions.options
        }
      ]
    })

    return config
  }
}