自定义 webpack 配置
优质
小牛编辑
141浏览
2023-12-01
- 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
}
}