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

Angular 2报错:(SystemJS) require is not defined 技术求助

解决SystemJS中"require is not defined"错误的方案

嘿,我之前搭旧版Angular项目的时候也碰到过一模一样的问题,这大概率是SystemJS的配置没跟上CommonJS模块的需求——毕竟你混着用Node.js/Express的后端模块和前端Angular代码,很容易出现模块加载的兼容问题。我给你几个实用的排查和解决步骤:

  • 第一步:安装必要的SystemJS插件
    因为require是CommonJS的语法,而SystemJS默认对CommonJS的支持不够完善,你需要安装专门的插件来处理:

    npm install systemjs-plugin-commonjs --save
    
  • 第二步:完善systemjs.config.js的配置
    把插件的映射和CommonJS的处理规则添加到配置里,参考示例如下:

    System.config({
      // 映射插件路径
      map: {
        'plugin-commonjs': 'node_modules/systemjs-plugin-commonjs/plugin-commonjs.js',
        // 如果用到Node.js核心模块(比如http、fs),添加空映射避免报错
        'http': '@empty',
        'fs': '@empty'
      },
      // 配置包的加载规则
      packages: {
        app: {
          format: 'register',
          defaultExtension: 'js'
        },
        // 标记node_modules下的包为CommonJS格式
        'node_modules': {
          format: 'commonjs'
        }
      },
      // 指定全局转译器为commonjs插件
      transpiler: 'plugin-commonjs'
    });
    

    另外要注意:确保在index.html里先引入SystemJS核心文件,再加载你的config脚本,顺序不能搞反:

    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').then(null, console.error.bind(console));
    </script>
    
  • 第三步:排查冲突的模块加载器
    检查你的index.html里有没有同时引入RequireJS或者其他模块加载工具,这些工具会和SystemJS争夺require这个全局变量,导致报错。如果有的话,去掉多余的加载器脚本就好。

  • 备选方案:替换旧的System.import语法
    如果你的项目可以适配较新的模块加载方式,也可以把index.html里的代码换成ES6动态导入语法,不过这需要确保环境支持:

    import('app').catch(err => console.error(err));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:45:36