Angular应用导入自定义JS文件时遇'Uncaught SyntaxError'错误求助
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.
Solution 1: Use ES6 Modules Directly (Recommended)
This is the cleanest, most modern approach:
- Remove the JS file from
angular-cli.json
Delete the../src/modules/myJs.jsentry from thescriptsarray—modules don't need to be registered here. - Verify your path alias (if using
@core)
Make sure yourtsconfig.jsonhas a path alias set up for@corepointing to your modules folder, like this:{ "compilerOptions": { "paths": { "@core/*": ["src/modules/*"] }, // ... other configs } } - 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); - Enable JS file support (if needed)
If TypeScript complains about importing a JS file, add"allowJs": trueto thecompilerOptionsin yourtsconfig.json.
Solution 2: Fallback to Global Variables (Not Recommended)
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:
- Rewrite your JS file
Remove theexportstatement and attach the object to thewindowglobal:// myJs.js window.someExport = { someExportProp: ... }; - 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

