ASP.NET(VB.Net)项目WebCompiler2022+编译JSX报错:exports is not defined
解决"Uncaught ReferenceError: exports is not defined"错误
问题原因
WebCompiler2022+默认将JSX编译成了CommonJS模块格式(生成exports相关代码),但你在HTML中给script标签添加了type="module",浏览器会按ES模块规则解析,无法识别CommonJS的exports语法,导致报错。
解决方案
1. 修改WebCompiler配置,输出ES模块格式
找到项目中的compilerconfig.json文件(WebCompiler自动生成),为Babel添加modules: false配置,阻止它将ES模块转换为CommonJS:
[ { "outputFile": "components/app.js", "inputFile": "components/app.jsx", "compiler": "babel", "babel": { "presets": [["@babel/preset-react", { "modules": false }]] } }, // 其他JSX文件的编译配置也需要同步修改 { "outputFile": "components/login.js", "inputFile": "components/login.jsx", "compiler": "babel", "babel": { "presets": [["@babel/preset-react", { "modules": false }]] } } ]
2. 修正React组件的调用方式
ES模块的导出不会挂载到全局作用域,你原来的App()调用无效,需要在模块脚本中引入并渲染组件:
- 删除HTML中的
<script type="text/javascript">App();</script> - 添加一个模块脚本负责渲染:
<script type="module"> import App from '/components/app.js'; import ReactDOM from '/scripts/reControls/react-dom.development.js'; // 将App组件渲染到root容器 ReactDOM.render(App(), document.getElementById('root')); </script>
3. 确保依赖引入兼容
你当前使用的是UMD版本的React(react.development.js),它会在全局暴露React变量,JSX文件中的import React from 'react';会被Babel正确处理,无需额外修改。如果后续切换到ES模块版本的React,只需将对应script标签改为type="module"并调整import路径即可。
内容的提问来源于stack exchange,提问作者amok khan
相关产品推荐
相关产品推荐

