webpack在生产中需要问题;未捕获的引用错误:require未定义

du7egjpx  于 12个月前  发布在  Webpack
关注(0)|答案(1)|浏览(109)

我已经构建了一个应用程序,使用HTML /CSS和Vanilla JS,并使用express.js来运行它。效果很好
现在使用webpack在互联网上的几个参考的帮助下构建软件包,这个expack帮助我构建,不知何故成功构建,当运行npm run start时,它在本地工作正常,并按预期工作,但在控制台中有错误
index.js:1未捕获的引用错误:require在807(index.js:1:21589)atwebpack_require(index.js:1:22045)at index. js:1:33214 at index.js:1:33289未定义
这不会停止任何本地,但在生产,由于这个错误,用户无法点击任何网页。
深入挖掘问题,我就到了这一行

807: e=>{
      e.exports = require("webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000")
    }

问题的原因(似乎)
生产URL:https://master.d1v0nmn943cmur.amplifyapp.com
下面是必需的文件内容,完整的代码可以在 * https://github.com/xkeshav/canvas.git * 上看到 master 分支

package.json

{
  "name": "canvas",
  "version": "1.0.0",
  "description": "trying with basic html css",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development --config webpack.dev.config.js",
    "server": "webpack --mode development --config webpack.server.config.js",
    "clean": "rd /s /q dist >nul 2>&1|echo.>null",
    "start": "node ./dist/server.js",
    "build": "npm run server && npm run dev",
    "build:dev": "webpack --mode=production --config webpack.dev.config.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/xkeshav/canvas.git"
  },
  "keywords": [
    "canvas",
    "varnmala",
    "kids learn"
  ],
  "author": "Keshav Mohta",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/xkeshav/canvas/issues"
  },
  "homepage": "https://github.com/xkeshav/canvas#readme",
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/eslint-parser": "^7.22.9",
    "@babel/register": "^7.0.0",
    "babel-loader": "^9.1.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.3",
    "eslint": "^8.30.0",
    "eslint-webpack-plugin": "^3.2.0",
    "html-loader": "^4.2.0",
    "html-webpack-plugin": "^5.5.0",
    "http-proxy-middleware": "^2.0.6",
    "json-server": "^0.17.1",
    "mini-css-extract-plugin": "^2.7.2",
    "style-loader": "^3.3.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-middleware": "^6.0.1",
    "webpack-hot-middleware": "^2.25.3",
    "webpack-node-externals": "^3.0.0"
  },
  "dependencies": {
    "@babel/preset-env": "^7.20.2",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "path": "^0.12.7",
    "request": "^2.88.2"
  }
}

.babelrc

{
    "presets": [
        "@babel/preset-env"
    ]
}

webpack.dev.js

const path = require("path");
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");

const plugins = require("./webpack.plugin.config");
const modules = require("./webpack.modules.config");

//console.log(process.argv.mode);
const BUILD_DIR = path.join(__dirname, "dist");
const SERVER_PATH = "/src/server/server-dev.js";
const SERVER_DIR = path.join(process.cwd(), SERVER_PATH);

const baseConfig = {
  entry: {
    index: ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000", "./src/index.js"],
    draw: ["./src/scripts/draw.js", "./src/scripts/alphabet.js", "./src/styles/draw.css"],
    varnmala: ["./src/scripts/varnmala.js", "./src/styles/varnmala.css"],
    canvas: ["./src/scripts/canvas.js", "./src/styles/canvas.css"],
    server: [SERVER_DIR],
  },
  performance: {
    hints: false,
  },
  devServer: {
    hot: true,
    contentBase: path.join(__dirname, "dist"),
  },
  output: {
    path: BUILD_DIR,
    publicPath: "/",
    filename: "[name].js",
    chunkFilename: "[name].js",
    assetModuleFilename: "assets/[hash][ext][query]",
    globalObject: `typeof self !== 'undefined' ? self : this`,
    clean: true,
  },
  mode: "production",
  target: "node", // "web"
  node: {
    // Need this when working with express, otherwise the build fails
    __dirname: false, // if you don't put this is, __dirname and __filename return blank or /
    __filename: false,
  },
  externals: [nodeExternals()],
  devtool: "eval-source-map",
  resolve: {
    extensions: [".html", ".js", ".json", ".css"],
  },
};

const config = Object.assign(baseConfig, { plugins, module: modules });

module.exports = config;

webpack.server.js

const path = require("path");
const nodeExternals = require("webpack-node-externals");

const SERVER_PATH = "./src/server/server-dev.js";
const config = {
  entry: {
    server: SERVER_PATH,
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: "/",
    filename: "[name].js",
  },
  devServer: {
    hot: true,
    historyApiFallback: true,
  },
  resolve: {
    extensions: [".js"],
  },
  mode: "production",
  target: "node",
  externals: [nodeExternals()], // Need this to avoid error when working with Express
  module: {
    rules: [
      {
        // Transpile ES6-8 into ES5
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
};
module.exports = config;

server/server-dev.js

// @ts-nocheck
import express from "express";
import fs from "fs";
import path from "path";
import { webpack } from "webpack";
import webpackDevMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import config from "../../webpack.dev.config.js";

const app = express();

const router = express.Router();

const currentDirectory = process.cwd(); // current directory

//console.log({ currentDirectory });

const DIST_DIR = path.join(path.resolve(currentDirectory, "dist"));

const HTML_DIR = path.join(DIST_DIR, "html");
const HTML_FILE = path.join(HTML_DIR, "index.html");
const compiler = webpack(config);

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);

app.use(webpackHotMiddleware(compiler));

app.use(express.static(HTML_DIR));

app.get("/home", (_, res) => {
  res.sendFile(HTML_FILE);
});

app.get("/about", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "about.html"));
});

app.get("/draw", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "draw.html"));
});

app.get("/varnmala", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "varnmala.html"));
});

app.get("/canvas", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "canvas.html"));
});

const readJson = (fileName) => {
  let jsonObjData = [];
  try {
    const jsonStringData = fs.readFileSync(path.join(DIST_DIR, "json", fileName));
    jsonObjData = JSON.parse(jsonStringData);
  } catch (err) {
    console.log(err);
  }
  return jsonObjData;
};

app.get("/bg/:key", (req, res) => {
  //console.log("params", req.params.key);
  const fileData = readJson("bg.json");
  const output = fileData.filter((f) => f.key === req.params.key.toLowerCase());
  //console.log({ output });
  res.status(200).send(output);
});

app.use("/", router);

const PORT = process.env.PORT || 3003;

app.listen(PORT, () => {
  console.log(`App listening to ${PORT}....`);
  console.log("Press Ctrl+C to quit.");
});

这是运行npm run build的输出

以下是我的几个疑问:
1.如何修复此webpack require问题,尝试了其他问题上建议的几种替代方案,但都不起作用
1.如果有丢失/错误的webpack配置,请指出
1.热重载不工作时,在HTML文件的变化,但工程的css,如何启用?

jtw3ybtb

jtw3ybtb1#

找到解决方案,此错误的原因是文件 * webpack.dev.config.js * 中的行

index: ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000", "./src/index.js"]

不知何故webpack5不支持热中间件了(我发现),所以改变这一点

index: ["./src/index.js"]

解决了我的问题。

相关问题