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

k6 TypeScript项目:跨目录导入致Webpack+Babel构建失败求助

解决k6性能测试跨目录导入主项目TypeScript文件的构建问题

核心问题分析

当前k6的Webpack+Babel转译流程仅处理自身目录内的文件,跨目录导入的主项目project/src文件未经过适配k6的转译规则处理,导致TypeScript语法(如ConfigType枚举)无法被正确识别。

解决方案步骤

1. 扩展Webpack配置,包含主项目目录转译规则

修改k6目录下的webpack.config.js,将主项目目录加入loader处理范围,同时可添加别名简化导入路径:

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        // 同时包含k6自身和主项目的TS文件
        include: [
          path.resolve(__dirname, 'src'),
          path.resolve(__dirname, '../project/src')
        ],
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [
                ['@babel/preset-env', { targets: { node: 'current' } }],
                '@babel/preset-typescript'
              ]
            }
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.tsx', '.js'],
    // 别名简化主项目文件导入
    alias: {
      '@project': path.resolve(__dirname, '../project/src')
    }
  }
};

2. 确保Babel正确处理TypeScript枚举

检查k6目录的babel.config.json,确认@babel/preset-typescript配置正确,未禁用枚举转换:

{
  "presets": [
    ["@babel/preset-env", { "targets": { "node": "current" } }],
    ["@babel/preset-typescript", { "isTSX": false, "allExtensions": true }]
  ]
}

3. 排除主项目中k6不兼容代码

主项目(Angular)文件可能包含浏览器或Angular专属API,需:

  • 仅导入纯TypeScript逻辑文件(如枚举、工具函数,不含Angular组件/服务)
  • 若必须导入含Angular依赖的文件,在Webpack中添加null-loader排除不兼容模块:
// webpack.config.js 新增规则
{
  test: /@angular\/core|@angular\/common/,
  use: 'null-loader'
}

4. 统一TypeScript配置规则

更新k6目录的tsconfig.json,包含主项目文件并启用枚举支持:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": [
    "src/**/*",
    "../project/src/**/*"
  ]
}

验证测试

修改配置后执行构建命令,尝试导入主项目枚举并运行测试:

// k6/src/test.ts
import { ConfigType } from '@project/enums/config-type';

export default function () {
  console.log(ConfigType.Production);
}

若构建成功且k6运行无报错,则跨目录导入问题已解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:17:08