多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
**问题**: 在webpack.config.js通过contentBase配置静态资源路径,使用 webpack 运行时( `npm run dev` )无法运行、 **发生场景**: 在 webpack.config.js 配置了devServer,通过contentBase 配置了静态资源的路径, 配置类似: ``` const path = require('path') // 处理绝对路径 module.exports = { mode: 'development', entry: path.join(__dirname, '/src/index.js'), // 入口文件 output: { path: path.join(__dirname, '/dist'), //打包后的文件存放的地方 filename: 'bundle.js' //打包后输出文件的文件名 }, devServer: { contentBase: './dist', // 此配置项在 5 版本已经修改 port: '8088', // 设置端口号为8088 } } ``` 使用 `npm run dev` 启动服务时报错误: ``` [webpack-cli] Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. - options has an unknown property 'contentBase'. These properties are valid: object { allowedHosts?, bonjour?, client?, compress?, devMiddleware?, headers?, historyApiFallback?, host?, hot?, http2?, https?, ipc?, liveReload?, magicHtml?, onAfterSetupMiddleware?, onBeforeSetupMiddleware?, onListening?, open?, port?, proxy?, server?, setupExitSignals?, setupMiddlewares?, static?, watchFiles?, webSocketServer? } ``` **原因及解析**: 错误信息中提示了contentBase 不是有效的配置项, 而且错误信息中也罗列了有效的配置项。的确,contentBase并不在其中。 这个原因是 Weback 5 将 contentBase的配置修改为 static了。 **解决方法**: 解决方法是将contentBase 修改为static。 `static:'./dist',` 官方推荐比较好的处理方式使用绝对路径的配置方式: ``` static: { //服务器所加载文件的目录 directory: path.join(__dirname, 'dist'), }, ``` 关于 devServer的详细配置, 可以参考: [https://webpack.docschina.org/configuration/dev-server/#devserverstatic](https://webpack.docschina.org/configuration/dev-server/#devserverstatic)