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

使用TypeScript+Webpack配置graphql-request时遇构建错误求助

解决graphql-request构建时的Module parse failed错误

问题原因

错误中的??是ES2020引入的空值合并运算符,你的Webpack配置默认排除了node_modules目录下的文件转译,而graphql-request@6.1.0的代码中使用了这个语法,导致Webpack无法解析该语法,抛出构建错误。

解决方案

方案一:转译graphql-request的代码

通过调整Webpack配置,让转译工具处理graphql-request的代码:

  1. 安装必要依赖:
npm install --save-dev babel-loader @babel/core @babel/preset-env
  1. 修改Webpack配置文件,添加JS转译规则:
const path = require('path');

module.exports = {
    entry: {
        MyLambda: 'LambdaPath',
    },
    target: 'node',
    output: {
        path: path.resolve(__dirname, 'terraform', 'dist'),
        filename: '[name].js',
        libraryTarget: 'commonjs2'
    },
    mode:'production',
    resolve: {
        extensions: ['.tsx', '.ts', '.js', '.json']
    },
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: ['ts-loader'],
                exclude: /node_modules/
            },
            // 新增规则处理graphql-request的JS代码
            {
                test: /\.js$/,
                include: /node_modules\/graphql-request/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            ['@babel/preset-env', { targets: { node: 'current' } }]
                        ]
                    }
                }
            }
        ]
    },
    externals: [/^aws-sdk/]
};

方案二:降低graphql-request版本

如果不想修改Webpack配置,可以降级到不使用ES2020语法的graphql-request版本,比如v5.x:

  1. 修改package.json中的版本:
"graphql-request": "^5.2.0"
  1. 重新安装依赖:
npm install

额外代码优化

你的业务代码中async函数使用了.then(),建议改为await风格,更符合异步函数的写法:

import { GraphQLClient, gql } from 'graphql-request'

export const getUser = async (authToken: AuthToken) => {
    const endpoint = `${process.env.Url}`;
    const query = gql`
         query {
            getUserInfo(Id: "5fc2ca90") 
            {
                name
                phone
            }
        }`;

    const client = new GraphQLClient(endpoint, { headers: { authorization: `Bearer ${authToken.value}` } });
    const data = await client.request(query);
    console.log(data);
    return data; // 建议返回数据供调用方使用
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 20:33:11