提问人:phpet 提问时间:3/24/2022 最后编辑:General Grievancephpet 更新时间:10/29/2023 访问量:9310
Webpack-dev-server“无法获取/”
Webpack-dev-server "Cannot GET /"
问:
我正在尝试让我的 webpack-dev-server 运行,但我在浏览器上总是遇到错误“无法获取 /”。 我知道有同样的错误,但它们都没有帮助我,所以现在我将试试运气:)
这些是我的webpack-config.js配置:
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/app.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.ts', '.js']
}
};
package.json:
{
"name": "ts",
"version": "1.0.0",
"description": "test",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"html-loader": "^3.1.0",
"html-webpack-plugin": "^5.5.0",
"lite-server": "^2.6.1",
"ts-loader": "^9.2.8",
"typescript": "^4.6.2",
"webpack": "^5.70.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"dependencies": {
"lodash": "^4.17.21"
}
}
从 index.html 中查找 bundle.js 的脚本如下所示:
<script type="module" src="dist/bundle.js"></script>
旁注:index.html 不像 bundle.js 那样在 dist 文件夹中,但我还是遇到了同样的错误。
更新|解决
如果有人会遇到同样的问题:
“webpack-dev-server” 从 5.0(左右)开始不再受支持。你必须把它改成
“start”: “webpack 服务”,
此外,我的 webpack-config.js 文件更改了,这成功了:
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/app.ts',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/dist/',
},
devServer: {
static: {
directory: path.join(__dirname, '/')
}
},
.
.
.
};
答:
0赞
Even Stensberg
3/25/2022
#1
尝试设置为output.publicPath
auto
https://webpack.js.org/guides/public-path/#automatic-publicpath
并通过 webpack 运行 dev server:
https://github.com/evenstensberg/webpack-react-boilerplate/blob/master/package.json#L9
您还需要一个 html 文件:
https://webpack.js.org/plugins/html-webpack-plugin/
评论
1赞
phpet
4/7/2022
感谢您的回答!消息“Cannot GET /”消失了,但我的项目不再被渲染了。当我使用 lite-server 时,它可以正常工作,但使用 webpack 则不行。我正在更新我的问题,以便更好地理解:)
评论
"webpack": "^5.74.0"
"webpack-cli": "^4.10.0"
"webpack-dev-server": "^4.10.0"
publicPath: '/dist'
/
devServer.static
/
mode: 'development'
mode: 'production'