我试图运行我的javascript应用程序与webpack开发服务器,我没有得到我的index.html
回来,相反,我得到Cannot GET /
在控制台GET http://localhost:8080/ 404 (Not Found)
这个错误。我四处寻找解决办法。我试图从应用程序路径中删除空间,并确保webpack配置output
内的路径与我在index.html
内的脚本标签中链接的路径相同。但仍然找不到正确的答案
webpack.config.js
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'public/scripts'),
filename: 'bundle.js'
},
module: {
rules: [{
test: /.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
}]
},
devServer: {
static: {
directory: path.resolve(__dirname, 'public'),
publicPath: '/scripts/'
}
}
}
package.json
{
"name": "boilerplate",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev-server": "webpack-dev-server --mode development",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/cli": "^7.15.7",
"@babel/core": "^7.15.8",
"@babel/preset-env": "^7.15.8",
"babel-loader": "^8.2.3",
"live-server": "^1.2.1",
"webpack": "^5.60.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.3.1"
}
}
使用HtmlWebpackPlugin
像HTML -webpack-plugin这样的包简化了HTML文件的创建,以服务于webpack包。
在webpack.config.js
中的用法:
const htmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: { path: `${__dirname}/build`, filename: "bundle.js" },
resolve: { modules: ["src", "node_modules"] },
module: {
rules: [
{ test: /.m?js$/, exclude: /node_modules/, loader: "babel-loader" },
],
},
plugins: [new htmlWebpackPlugin({ template: "./src/index.html" })],
};
请注意,我的回答假设所有静态文件都在src文件夹中。