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

如何在Vite+React项目中集成.NET 7 WebAssembly?

Vite 集成 .NET 7 WebAssembly 配置方案

核心思路

因为 .NET WebAssembly 的 dotnet.js 会动态加载同目录下的 .wasm 和 .dll 文件,且这些文件的路径依赖不能被 Vite 重命名或修改,所以需要:

  1. 将整个 AppBundle 作为静态资源原样复制到打包后的目录
  2. 通过别名映射实现代码中的"虚拟导入",同时区分开发/生产环境的路径
  3. 标记相关文件为外部依赖,避免 Vite 解析内部动态导入导致报错

具体配置步骤

1. 静态资源自动复制(可选)

安装 vite-plugin-static-copy 插件,自动将 .NET 生成的 AppBundle 复制到打包目录,避免手动复制:

npm install vite-plugin-static-copy --save-dev

2. 修改 Vite 配置文件

在 vite.config.js 中添加以下配置:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { viteStaticCopy } from 'vite-plugin-static-copy';

export default defineConfig({
  plugins: [
    react(),
    // 自动复制 AppBundle 到打包后的 MyAppBundle 目录
    viteStaticCopy({
      targets: [
        {
          src: '../../wasm/bin/Release/net7.0/browser-wasm/AppBundle/**/*', // 替换为你的 .NET AppBundle 实际路径
          dest: 'MyAppBundle'
        }
      ]
    })
  ],
  resolve: {
    // 配置别名,实现"虚拟导入"映射
    alias: {
      'some-file': process.env.NODE_ENV === 'production'
        ? '/MyAppBundle/dotnet.js' // 生产环境固定路径
        : '../../wasm/bin/Release/net7.0/browser-wasm/AppBundle/dotnet.js' // 开发环境本地路径
    }
  },
  build: {
    // 标记该路径为外部依赖,不打包进 bundle,避免解析动态导入报错
    rollupOptions: {
      external: ['/MyAppBundle/dotnet.js']
    },
    // 确保 Vite 识别这些文件类型,不触发错误处理
    assetsInclude: ['**/*.wasm', '**/*.dll']
  }
});

3. 代码中使用虚拟导入

在 React 组件或 JS 文件中直接通过别名导入:

import { dotnet } from 'some-file';

// 初始化 .NET WebAssembly
async function initDotnet() {
  const dotnetInstance = await dotnet.create();
  // 示例:获取 .NET 程序集导出的方法
  const exports = await dotnetInstance.getAssemblyExports('YourAssemblyName.dll');
  // 调用导出的 .NET 方法
  // exports.YourNamespace.YourMethod();
}

// 页面加载时执行初始化
initDotnet();

手动复制替代方案(无需插件)

如果不想安装插件,可以直接将 .NET 生成的 AppBundle 文件夹复制到项目的 public/MyAppBundle 目录下,Vite 会自动将 public 目录下的文件原样复制到打包后的根目录,此时只需保留 resolve.alias 和 build.rollupOptions 配置即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:15:18