You need to enable JavaScript to run this app. 如何使用Webpack4结合Pug模板引擎成功构建NodeJS项目
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Webpack4结合Pug模板引擎成功构建NodeJS项目

项目构建问题汇总

项目基础信息

该项目为可通过localhost:5000访问的REST API,构建排查已持续近2天未定位到可行方案,因所有问题互相关联,合并提交以提供完整上下文。
项目目录结构如下:

controllers
init
  - db.js
models
public
  - css
routes
views
  - layout.pug
  - index.pug
.babelrc
.env
app.js
start.js
package.json
webpack.server.config.js
webpack.prod.config.js

核心代码与配置现状

  • 项目入口为start.js,承担数据库初始化、Express实例启动逻辑,现有代码为:
    import InitializeDB from "./init/db";
    import app from "./app";
    
    InitializeDB();
    app.set("port", process.env.PORT || 3000);
    const server = app.listen(app.get("port"), () => {
      console.log(`Express running → PORT ${server.address().port}`);
    });
    
  • app.js负责初始化Express实例、挂载相关中间件,最终导出初始化后的app常量
  • init/db.js导出默认函数,用于完成数据库初始化连接
  • 为支持ES6导入语法,已安装依赖@babel/core @babel/cli @babel/preset-env @babel/node,.babelrc配置为:
    {
      "presets": ["@babel/preset-env"]
    }
    
  • package.json脚本配置为:
    "scripts": {
      "build": "rm -rf dist && webpack --mode production --config webpack.server.config.js && webpack --mode production --config webpack.prod.config.js",
      "start": "node ./dist/server.bundle.js",
      "watch": "nodemon --exec babel-node start.js --ignore public/",
      "start:dev": "concurrently \"npm run test\" \"npm run watch\"",
      "test": "echo \"Testing...\""
    }
    

本地执行npm run start:dev时所有功能可正常运行,但后续原生Node启动、Webpack生产构建流程均报错。

全链路报错详情

原生Node直接启动报错

  • 直接执行node ./start.js,出现提示:(node:149228) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
  • 按提示在package.json中添加"type": "module"配置后,再次执行npm run start:dev,出现模块找不到错误:
    internal/modules/run_main.js:54
        internalBinding('errors').triggerUncaughtException(
                                  ^
    
    Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'G:\apps\myproject\init\db' imported from G:\apps\myproject\start.js
    Did you mean to import ../init/db.js?
    

Webpack生产构建报错

现有Webpack配置如下:

  • webpack.server.config.js:
    const path = require("path");
    const webpack = require("webpack");
    const nodeExternals = require("webpack-node-externals");
    
    module.exports = {
      entry: { server: "./start.js" },
      output: {
        path: path.join(__dirname, "dist"),
        publicPath: "/",
        filename: "[name].bundle.js",
      },
      target: "node",
      node: {
        __dirname: false,
        __filename: false,
      },
      externals: [nodeExternals()],
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            use: { loader: "babel-loader" },
          },
        ],
      },
    };
    
  • webpack.prod.config.js:
    const path = require("path");
    const webpack = require("webpack");
    const HtmlWebPackPlugin = require("html-webpack-plugin");
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
    const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
    
    module.exports = {
      entry: { app: "./start.js" },
      output: {
        path: path.join(__dirname, "dist"),
        publicPath: "/",
        filename: "[name].bundle.js",
      },
      target: "node",
      devtool: "source-map",
      optimization: {
        minimizer: [
          new UglifyJsPlugin({ cache: true, parallel: true, sourceMap: true }),
          new OptimizeCSSAssetsPlugin({}),
        ],
      },
      module: {
        rules: [
          { test: /\.pug$/, use: ["pug-loader"] },
          { test: /\.css$/, use: [MiniCssExtractPlugin.loader, "css-loader"] },
          { test: /\.(png|svg|jpg|gif)$/, use: ["file-loader"] },
          { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
        ],
      },
      plugins: [
        new HtmlWebPackPlugin({ template: "./views/index.pug" }),
        new MiniCssExtractPlugin({ filename: "[name].css", chunkFilename: "[id].css" }),
      ],
    };
    

曾尝试将webpack.prod.config.js的target配置从node调整为web,未解决问题。

构建执行过程中的报错分两种场景:

  1. 保留package.json中"type": "module"配置时,执行npm run build,报ESM加载错误:
    Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: G:\apps\myproject\webpack.server.config.js
    require() of ES modules is not supported.
    require() of G:\apps\myproject\webpack.server.config.js from G:\apps\myproject\node_modules\webpack-cli\bin\utils\convert-argv.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
    Instead rename webpack.server.config.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from G:\apps\myproject\package.json.
    
  2. 移除package.json中"type": "module"配置后,再次执行npm run build,出现两类批量报错:
    • 大量Critical dependency: the request of a dependency is an expression提示
    • 多个Module not found: Error: Can't resolve 'net' in 'G:\apps\myproject\node_modules\...'提示

内容的提问来源于stack exchange,提问作者Kingsley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.03 04:36:02