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

如何配置ASP.NET Core 6 MVC项目支持TypeScript的import与export?

在ASP.NET Core 6 MVC中使用TypeScript模块的问题
  • 遇到的情况:给ASP.NET Core 6 MVC项目添加TypeScript支持,使用import/export导入导出模块时,代码可正常编译,但浏览器报错,当前提示Uncaught ReferenceError: define is not defined(使用AMD模块类型时),切换其他模块类型还会出现exports is not defined
  • 需求:不想用Webpack将文件打包为单个文件,开发阶段希望保持文件独立
  • 当前tsconfig.json配置:
{ 
  "compilerOptions": {
    "target": "ES6",                               
    "module": "amd",                             
    "rootDir": "./scripts",                      
    "moduleResolution": "node",                  
    "sourceMap": true,                           
    "outDir": "./wwwroot/js/",                   
    "esModuleInterop": true,                     
    "forceConsistentCasingInFileNames": true,   
    "strict": true,                              
    "skipLibCheck": true                         
  }
}
  • 测试代码test.ts:
import convert from "convert";
export function add(x: number, y: number): number
{
    return x + y;
}

解决方案1:改用ES模块(推荐,无需额外加载器)

现代浏览器原生支持ES模块,只需调整配置和页面引用方式:

  1. 修改tsconfig.json中的module为ESNext或ES6:
{ 
  "compilerOptions": {
    "target": "ES6",                               
    "module": "ESNext",  // 切换为ES模块类型
    "rootDir": "./scripts",                      
    "moduleResolution": "node",                  
    "sourceMap": true,                           
    "outDir": "./wwwroot/js/",                   
    "esModuleInterop": true,                     
    "forceConsistentCasingInFileNames": true,   
    "strict": true,                              
    "skipLibCheck": true                         
  }
}
  1. 在Razor视图(如_Layout.cshtml或具体页面)中引用编译后的JS文件时,添加type="module"属性:
<script type="module" src="~/js/test.js"></script>
  1. 注意:使用第三方库(如convert)时,需确保其支持ES模块。若是npm安装的包,可能需要调整导入路径,或开发阶段直接使用CDN引入对应的ES模块版本。

解决方案2:保留AMD模块,引入RequireJS加载器

若坚持使用AMD模块,需在页面中引入RequireJS来处理define函数:

  1. 将RequireJS下载至wwwroot/lib/requirejs/目录,或直接通过CDN引入:
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
  1. 配置RequireJS的模块路径,确保能找到convert等第三方库:
<script>
    require.config({
        baseUrl: '/js',
        paths: {
            'convert': '../lib/convert/convert' // 替换为convert库的实际存放路径
        }
    });
    // 加载test模块并调用方法
    require(['test'], function(test) {
        console.log(test.add(1, 2));
    });
</script>
  1. 需确保第三方库(如convert)存在AMD版本,或通过npm安装后将正确文件复制至wwwroot目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:35:09