You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移Cloud SQL Node.js Connector遇crypto模块依赖报错求助

Cloud SQL Node.js Connector 报错:Support to node crypto module is required

我们正在迁移到官方Cloud SQL Node.js Connector,但测试新连接配置时出现报错:

Support to node crypto module is required
报错位置为node_modules/@google-cloud/cloud-sql-connector/src/node-crypto.ts:26:11

运行环境为Node.js v20,日志显示当前crypto模块可用,且连接器已从@google-cloud/cloud-sql-connector正确加载,但调用connector.getOptions()时仍触发上述错误。

相关代码片段

Cloud SQL Connector 包内报错代码

对应的包内编译后代码如下:

Object.defineProperty(exports, "__esModule", { value: true });
exports.cryptoModule = cryptoModule;
const errors_1 = require("./errors");
async function cryptoModule() {
    // check for availability of crypto module and throws an error otherwise
    // ref: https://nodejs.org/dist/latest-v18.x/docs/api/crypto.html#determining-if-crypto-support-is-unavailable
    let crypto;
    try {
        crypto = await import('node:crypto');
        /* c8 ignore next 6 */
    }
    catch (err) {
        throw new errors_1.CloudSQLConnectorError({
            message: 'Support to node crypto module is required',
            code: 'ENOCRYPTOMODULE',
        });
    }
    return crypto;
}
//# sourceMappingURL=node-crypto.js.map

报错触发代码

报错发生在以下代码执行时:

console.log("[sql-connector] crypto available:", typeof require("crypto"));
console.log("[sql-connector] connector loaded from:", require.resolve("@google-cloud/cloud-sql-connector"));

const clientOpts = await connector.getOptions({
    instanceConnectionName: config.connect.cloudConnectionName,
    authType: AuthTypes.IAM,
    ipType: IpAddressTypes.PRIVATE, 
});

当前Webpack配置

我们的Webpack配置如下:

const webpack = require("webpack");
const NodeExternals = require("webpack-node-externals");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const path = require("path");

let {
    TRAVIS_BRANCH,
    TRAVIS_COMMIT,
    TRAVIS_COMMIT_MESSAGE,
    TRAVIS_BUILD_NUMBER,
    TRAVIS_BUILD_ID,
} = process.env;

let buildInfo = {
    started: Date.now(),
    buildId: isNaN(parseInt(TRAVIS_BUILD_ID)) ? null : parseInt(TRAVIS_BUILD_ID),
    buildNumber: isNaN(parseInt(TRAVIS_BUILD_NUMBER))
        ? null
        : parseInt(TRAVIS_BUILD_NUMBER),
    commitMessage: TRAVIS_COMMIT_MESSAGE || null,
    commit: TRAVIS_COMMIT || null,
    branch: TRAVIS_BRANCH || "local",
};

module.exports = {
    mode: "production",
    entry: { index: "./index.js" },
    optimization: {
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    mangle: false, // <-- IMPORTANT, we use func.name for things
                },
            }),
        ],
    },
    output: {
        filename: "[name].js",
        libraryTarget: "commonjs",
        devtoolModuleFilenameTemplate: "[resource-path]",
    },
    target: "node",
    module: {
        rules: [
            {
                test: /\.(jsx?)$/,
                exclude: /node_modules/,
                use: ["swc-loader"],
            },
            {
                test: /\.(tsx?)$/,
                exclude: /node_modules/,
                use: {
                    loader: "swc-loader",
                    options: {
                        jsc: {
                            parser: {
                                syntax: "typescript",
                            },
                        },
                    },
                },
            },
        ],
    },
    resolve: {
        extensions: [".js", ".ts", ".json"],
        alias: {
            "@Api": path.resolve(process.cwd(), "src/api"),
            "@Models": path.resolve(process.cwd(), "src/api/models"),
            "@Types": path.resolve(process.cwd(), "src/api/types"),
            "@Consts": path.resolve(process.cwd(), "src/api/consts"),
            "@Utils": path.resolve(process.cwd(), "src/api/utils"),
            "@Functions": path.resolve(process.cwd(), "src/functions"),
        },
    },
    devtool: "source-map",
    plugins: [
        new webpack.BannerPlugin({
            raw: true,
            banner: "require('source-map-support').install();",
        }),
        new webpack.DefinePlugin({
            "process.env.BUILD_INFO": JSON.stringify(buildInfo),
        }),
        new CopyWebpackPlugin({
            patterns: [{ from: "package.json" }],
        }),
    ],
    externals: [NodeExternals()],
};

已尝试的解决方案

  • 使用不同的认证/IP类型
  • 验证cloudConnectionName格式符合my-project:europe-west1:db-name要求
  • 配置Webpack避免polyfillcrypto:
    fallback: {
     crypto: false,
    },
    
    // 同时在externals中配置
    externals: [NodeExternals(), {crypto: false}],
    
  • 确认Webpack的target设置为"node"

需求

希望找到无需通过npx patch-package修改包内代码(将import改为CommonJS的require格式)的解决方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:27:07