运行webpack-dev-server报错 Cannot find module 'webpack/schemas/WebpackOptions.json'
今天有空,就去梳理一下webpack的基础知识和配置,然后找了一篇博文跟着步骤走,到‘使用webpack-dev-server’这一步时,运行npm start报错:Cannot find module 'webpack/schemas/WebpackOptions.json'
博文教程:https://segmentfault.com/a/1190000010871559#articleHeader15
我的配置如下:
packge.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.21.0",
"webpack": "^3.4.1",
"webpack-cli": "^2.1.4",
"webpack-dev-server": "^3.1.4" //关键第一句
},
"dependencies": {
"lodash": "^4.17.10"
}
}
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
// const webpack = require('webpack');
module.exports = {
devtool: 'inline-cheap-module-source-map',
entry: {
app: './src/index.js',
print: './src/print.js'
},
output: {
filename: '[name].bundle.js',
path:path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [
'file-loader'
]
}
]
},
devServer:{
contentBase: path.resolve(__dirname, 'dist'),//关键第二句
},
plugins: [
new HtmlWebpackPlugin({
title:'webpack demo',
filename:'index.html'
}),
new CleanWebpackPlugin(['dist']),
]
}
开始网上的很多解决方案都不是我的问题所在,因为我的webpack全局、局部都安装好了。后来猜测:我的webpack版本是参照教程里面安装的3.4.1,而webpack-dev-server是默认安装的最新的3.1.4,报错说找不到WebpackOptions.json文件,有可能是版本不配套,现在webpack最新版本是4.9.1了,最新的webpack应该有WebpackOptions.json文件,所以,3.1.4的webpack-dev-server是跟4.X.X的webpack配套的,所以测试:
将webpack-dev-server降级:
npm uninstall webpack-dev-server
npm i --save-dev webpack-dev-server@2.9.7
再运行命令:npm start
真的成功了!
所以我现在的package.json:
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.21.0",
"webpack": "^3.4.1",
"webpack-cli": "^2.1.4",
"webpack-dev-server": "^2.9.7"
},
"dependencies": {
"lodash": "^4.17.10"
}
}
总结:这个错误网上搜索的结果,大部分是说因为webpack没局部安装,或者start命令配置错误,而实际上我的报错原因是,webpack和webpack-dev-server版本不配套导致,所以有时候报错要能静下来自己分析一下原因也是好的。另外,问题是解决了,要证明我的猜测完全正确,得下次安装了webpack4,看看如果有WebpackOptions.json文件,那就猜对了,今天先接着把3弄完。
更多推荐
所有评论(0)