Angular中JS文件管理方法及MEAN应用配置angular.cli.json调用自定义JS
Hey there! Let's get your jQuery setup sorted for your MEAN app. Since you've already installed jQuery via npm, here's exactly what you need to do to hook up both the core library and your custom script in angular.cli.json:
Step 1: Add the scripts section to your apps config
Your current config snippet cuts off, but you'll need to add a scripts array inside the existing apps object. This is where you'll reference both jQuery and your custom JS file—order matters here (load jQuery first, since your custom script depends on it).
Step 2: Update your angular.cli.json with the correct paths
Here's how your complete apps configuration should look, with the new scripts section added:
"apps": [ { "root": "angular/src", "outDir": "angular/dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html", "main": "main.ts", "polyfills": "polyfills.ts", "test": "test.ts", "tsconfig": "tsconfig.app.json", "testTsconfig": "tsconfig.spec.json", "scripts": [ "../node_modules/jquery/dist/jquery.min.js", "assets/js/your-custom-jquery-script.js" ] } ]
Important Details:
- The jQuery path uses
../because your app's root is set toangular/src—we need to move up one directory to reach thenode_modulesfolder where npm installed jQuery. - Replace
your-custom-jquery-script.jswith the actual filename of your script inangular/src/assets/js/. - Don't forget to restart your Angular development server after saving these changes—config updates to
angular.cli.jsonwon't take effect until you do a full restart.
Quick Verification Tip
To make sure everything's loaded correctly, you can add a quick check in one of your components or the browser console:
// In a component's ngOnInit method ngOnInit() { if (window.jQuery) { console.log('jQuery and custom script are loaded!'); } }
内容的提问来源于stack exchange,提问作者Sta-Dev

