首页 > 解决方案 > 为什么将 Node.js 后端 API 与 Webpack 捆绑失败并显示“TypeError:i is not a function”?

问题描述

我正在尝试创建一个 docker 容器来容纳我的前端(React)和后端(快速 REST 服务),但是我将后端与 Webpack 捆绑在一起的努力未能执行,声称“我不是一个函数”。我应该清楚,这还没有在 Docker 中运行。我只是想先在我的开发环境中手动执行它。

我只是简单地 webpack,然后尝试直接运行捆绑的 js(例如节点 ./dist/server.bundle.js)。这是我的 webpack.config.js:

{
    "name": "test-backend",
    "version": "1.0.0",
    "description": "Test Backend",
    "scripts": {
        "start": "nodemon ./server.js",
        "build": "webpack",
        "debug": "node --inspect ./server.js",
        "debug-brk": "node --inspect-brk ./server.js"
    },
    "dependencies": {
        "body-parser": "1.19.0",
        "cors": "2.8.5",
        "express": "4.17.1",
        "express-jwt": "5.3.3",
        "ioredis": "4.17.3",
        "jsonwebtoken": "8.5.1",
        "ldapjs": "2.0.0",
        "ldapjs-client": "0.1.1",
        "lodash": "4.17.19",
        "node-cache": "5.1.0",
        "redis": "3.0.2",
        "rootpath": "0.1.2",
        "superagent": "5.2.2",
        "uuid": "8.2.0"
    },
    "devDependencies": {
        "nodemon": "2.0.4",
        "webpack": "^4.43.0",
        "webpack-cli": "^3.3.12",
        "webpack-node-externals": "^2.5.2"
    }
}

错误行/位置指向我捆绑的后端 js 中看起来像“crypto”和其他人的导入:

TypeError: i is not a function
    at Object.<anonymous> (/var/test/test-services/images/test-unified/backend/dist/server.bundle.js:333:90327)
    at n (/var/test/test-services/images/test-unified/backend/dist/server.bundle.js:1:110)
...

...var r=i("crypto"),a=i("fs"),o=i("util"),s=i("path"),...

我觉得 webpacking 没有包含必要的节点模块。我的 webpack.config.js 很可能遗漏了一些东西:

const path = require('path');

module.exports = {
  entry: './server.js',
  mode: 'production',
  target: 'node',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'server.bundle.js'
  }
};

有一些关于捆绑服务器端 js 的示例和教程,但它们只是示例,仅包含没有 Express 和其他模块的简单 server.js 代码。

任何提示都非常感谢。谢谢你。

标签: node.jswebpack

解决方案


我将通过分享我的 webpack.config.js 更改来结束这个问题:

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

module.exports = {
  entry: './server.js',
  mode: 'production',
  target: 'node',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'server.bundle.js'
  },
  externals: [nodeExternals()]
};

使用 webpack-node-externals 基本上会期望 node_modules 是本地相对的,而不是尝试将它们捆绑在一起。您的源将是,但不是外部模块。我可以忍受这一点。

回答 jonsharpe 关于为什么捆绑 Node.js 应用程序的问题主要是为了简化我的 docker 容器,并通过打包和优化我的应用程序来保证安全。我在应用程序中有一堆各种组件、服务和控制器,现在它们都是一个文件。

在提到需要和外部节点的问题之后,我找到了本指南。她还使用了 webpack-node-externals:https ://jasminexie.github.io/using-webpack-for-node-backend/


推荐阅读