报错Dev Server has been initialized using an options object that does not match

在学习Webpack时遇到DevServer配置报错,内容涉及contentBase和publicPath。经过查证,发现是由于使用的Webpack版本为4.8.1,而配置参考的是不同版本的文档。Webpack v3与v4中,devServer的contentBase和publicPath等选项已调整到static配置下。理解这一变化对于正确配置Webpack至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Dev Server has been initialized using an options object that does not match

笔者跟着B站up学习webpack时,出现了如下错误
在这里插入图片描述
报错中有说到,options中有一个未知的属性“contentBase” 事实上,不仅是我配置的contentBase报错了,我配置的publicPath也报错了。

devServer:{
     hot:true,
     publicPath:'/'
     contentBase:path.resolve(__dirname,'public')
},

初步怀疑是webpack版本的问题,所以我找出webpack的官方文档1,奇怪的是,这个文档里有publicPath和contentBase配置。

而在这个官方文档2中却把publicPath放到了static目录下,而且没有contentBase配置。
在这里插入图片描述
查阅第二个官方文档时,发现了下面这段话。我查看了我的webpack版本,是4.8.1的,所以使用该配置不会报错。
在这里插入图片描述
我去github上翻看了v3到v4的迁移指南

在v3中

module.exports = {
  devServer: {
    contentBase: path.join(__dirname, "public"),
    contentBasePublicPath: "/serve-content-base-at-this-url",
    serveIndex: true,
    watchContentBase: true,
    watchOptions: {
      poll: true,
    },
  },
};

而在v4中
contentBase/contentBasePublicPath/serveIndex/watchContentBase/watchOptions/staticOptions 等配置已经移到了static配置中。

module.exports = {
  devServer: {
    static: {
      directory: path.resolve(__dirname, "static"),
      staticOptions: {},
      // Don't be confused with `devMiddleware.publicPath`, it is `publicPath` for static directory
      // Can be:
      // publicPath: ['/static-public-path-one/', '/static-public-path-two/'],
      publicPath: "/static-public-path/",
      // Can be:
      // serveIndex: {} (options for the `serveIndex` option you can find https://github.com/expressjs/serve-index)
      serveIndex: true,
      // Can be:
      // watch: {} (options for the `watch` option you can find https://github.com/paulmillr/chokidar)
      watch: true,
    },
  },
};

//如果你有多个静态文件夹,提供一个对象数组
module.exports = {
  //...
  devServer: {
    static: [
      {
        directory: path.join(__dirname, "assets"),
        publicPath: "/serve-public-path-url",
      },
      {
        directory: path.join(__dirname, "css"),
        publicPath: "/other-serve-public-path-url",
      },
    ],
  },
};

总结

  • publicPath变成了static下的publicPath
  • contentBase变成了static下的directory
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焦妮敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值