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

Nx构建Webpack应用远程类型仅为压缩包,如何正确配置?

解决Nx + Module Federation远程类型生成压缩包的问题

1. 配置ModuleFederationPlugin的类型生成选项

直接在应用Webpack配置的ModuleFederationPlugin中添加类型生成相关配置,禁用压缩并指定输出目录,确保生成.d.ts格式的类型文件:

new ModuleFederationPlugin({
  name: 'info_plus',
  filename: 'remoteEntry.js',
  runtime: false,
  // 新增类型生成配置
  types: {
    outputPath: path.join(__dirname, '../../dist/apps/info_plus/types'), // 指定类型文件输出目录
    federationTypes: true, // 启用联邦类型生成
    compress: false, // 禁用压缩包输出
  },
  exposes: {
    './InfoPlusApp': './src/app/App.tsx',
  },
  shared: {
    react: {
      singleton: true,
      requiredVersion: '^18.0.0',
    },
    'react-dom': {
      singleton: true,
      requiredVersion: '^18.0.0',
    },
  },
}),

2. 确保TypeScript生成声明文件

在项目的tsconfig.json(或根目录的tsconfig.base.json)中开启声明文件生成:

{
  "compilerOptions": {
    "declaration": true,
    "emitDeclarationOnly": false,
    "declarationMap": false // 可选,不需要映射文件可关闭
  }
}

3. 检查Nx构建配置

打开项目的project.json,找到build目标,确认没有开启类型文件压缩打包的配置:

{
  "targets": {
    "build": {
      "executor": "@nrwl/webpack:webpack",
      "options": {
        // 移除或注释掉任何与类型压缩相关的配置,比如:
        // "compress": true,
        // "archive": "tgz"
      }
    }
  }
}

4. 调整Webpack配置避免处理类型文件

在通用Webpack配置中添加规则,排除.d.ts文件的编译和拆分处理:

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const path = require('path');

module.exports = {
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
    plugins: [
      new TsconfigPathsPlugin({
        configFile: path.resolve(__dirname, './tsconfig.base.json'),
      }),
    ],
  },
  optimization: {
    runtimeChunk: false,
    splitChunks: {
      chunks: 'async',
      exclude: /\.d\.ts$/ // 排除类型文件的代码拆分
    },
  },
  module: {
    rules: [
      {
        test: /\.d\.ts$/,
        use: 'ignore-loader' // 让Webpack忽略类型文件的编译
      }
    ]
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:10:57