【问题标题】:Using Webpack with an existing vanilla JS project results in an `Cannot GET /` error将 Webpack 与现有的 vanilla JS 项目一起使用会导致 `Cannot GET /` 错误
【发布时间】:2021-11-29 03:29:40
【问题描述】:

我的简单 JS Web 应用程序有这样的文件结构:

myproject
│   README.md
│   .gitignore
|   index.html    
└───style
│   │   style.css
│   │   style.scss
│   │   style.css.map   
│   
└───js
    │   javascript1.js
    │   javascript2.js
    |   javascript3.js
│   
└───assets
    │   someimage.png
    │   someimage2.png
    |   ...

到目前为止,我的工作流程是将 SCSS 编译为 CSS,然后在浏览器中打开 index.html。我想让工作流程更高效(自动 SCSS 编译、热或实时重新加载、JS 最小化等),所以我正在尝试使用一些构建工具,如 Webpack。我关注了a guide,并将例如这个文件webpack.config.js添加到我的项目的根目录中:

module.exports = {
  entry: [
    './js/javascript1.js',
    './js/javascript2.js',
    './js/javascript3.js',
    './style/style.css'
  ],
  output: {
    path: __dirname,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "script-loader"
        }
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: "style-loader"
          },
          {
            loader: "css-loader",
            options: {
            }
          }
        ]
      }
    ]
  }
};

server.js:

const express = require('express');
const path = require('path');
const port = process.env.PORT || 8080;
const app = express();
app.use(express.static(__dirname));//
app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(port);

并将一个空的bundle.js 文件添加到项目根目录,并将以下标记添加到我现有的index.html

<script src="bundle.js"></script>

现在,在使用脚本添加 package.json 文件后

"dev": "webpack-dev-server --mode development --open"`

在运行npm installnpm dev run 之后,项目编译(根据VS Code),但我在localhost:8080 上得到以下页面:

Cannot GET /

我花了整整一个工作日试图弄清楚这一切。为什么会出现此错误?

【问题讨论】:

    标签: javascript webpack package.json


    【解决方案1】:

    \dist 中创建一个新的HTML 页面,从正确的位置引用bundle.js 文件并将以下内容添加到webpack.config.js 中的module.exports

    devServer: {
      static: './dist'
    },
    

    最终成功了。

    【讨论】:

      猜你喜欢
      • 2017-09-12
      • 2013-11-11
      • 2018-06-12
      • 2020-05-04
      • 2017-07-28
      • 2011-06-30
      • 2020-02-08
      • 2014-12-25
      • 1970-01-01
      相关资源
      最近更新 更多