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

Angular应用导入自定义JS文件时遇'Uncaught SyntaxError'错误求助

Fixing "Uncaught SyntaxError: Unexpected token export" in Angular with Custom JS Files

Hey there, let's break down why you're running into this error and how to fix it!

The Root Cause

You added your ES6 module-style JS file (export const someExport = {...}) to the scripts array in angular-cli.json—but that's not how ES6 modules work in Angular. The scripts array is meant for global, non-module scripts (like legacy libraries that attach variables to window). When Angular CLI loads files from scripts, it doesn't process ES6 export/import syntax, so the browser throws a syntax error when it encounters the unrecognized export keyword.


This is the cleanest, most modern approach:

  1. Remove the JS file from angular-cli.json
    Delete the ../src/modules/myJs.js entry from the scripts array—modules don't need to be registered here.
  2. Verify your path alias (if using @core)
    Make sure your tsconfig.json has a path alias set up for @core pointing to your modules folder, like this:
    {
      "compilerOptions": {
        "paths": {
          "@core/*": ["src/modules/*"]
        },
        // ... other configs
      }
    }
    
  3. Import the module in your component
    Now you can safely import your export in the component:
    import { someExport } from '@core/myJs';
    
    // Use it like normal
    console.log(someExport.someExportProp);
    
  4. Enable JS file support (if needed)
    If TypeScript complains about importing a JS file, add "allowJs": true to the compilerOptions in your tsconfig.json.

If you absolutely need to load the file via the scripts array (e.g., for legacy code), convert your JS file to use global variables instead of ES6 modules:

  1. Rewrite your JS file
    Remove the export statement and attach the object to the window global:
    // myJs.js
    window.someExport = { someExportProp: ... };
    
  2. Declare the global variable in your component
    Tell TypeScript about the global variable to avoid type errors:
    // At the top of your component file
    declare const someExport: { someExportProp: any }; // Replace `any` with a specific type if possible
    
    // Then use it
    ngOnInit() {
      console.log(someExport.someExportProp);
    }
    

This approach is not ideal because it bypasses Angular's modular system and reduces type safety.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:13:39