Angular 2/5中非模块化外部JavaScript库的导入方法咨询
Hey there, let's tackle this problem step by step. I've run into similar issues with external JS libraries in Angular before, so here are a few reliable methods that should work for you with the Kakao SDK:
This is the most straightforward approach, just like how you'd add scripts in regular HTML:
- Open your
src/index.htmlfile - Add the script tag in the
<head>section or at the end of<body>:
<script src="http://developers.kakao.com/sdk/js/kakao.min.js"></script>
Then, in your component's .ts file, you just need to declare the global Kakao variable to avoid TypeScript compilation errors:
declare let Kakao: any; @Component({ // Your component metadata }) export class YourComponent { ngOnInit() { // Now you can use Kakao's APIs normally if (!Kakao.isInitialized()) { Kakao.init('your-app-api-key'); } } }
Since the script loads globally, once index.html finishes loading, the Kakao object will be available in the global scope. The declare statement just tells TypeScript this variable exists.
For Angular 5, you'll modify the .angular-cli.json file (Angular 6+ uses angular.json instead):
- Locate the
scriptsarray in the configuration, and add the Kakao SDK URL to it:
"scripts": [ "http://developers.kakao.com/sdk/js/kakao.min.js" ]
Just like the first method, add declare let Kakao: any; in your component file, and you'll be able to use the SDK across your app. This approach lets Angular manage script loading order, which is great for libraries you need globally.
Your earlier dynamic loading attempt probably failed because you tried using Kakao before the script finished loading. Here's a corrected way to handle dynamic loading with promises, ensuring the script is ready before you use it:
declare let Kakao: any; @Component({ // Your component metadata }) export class YourComponent { ngOnInit() { this.loadKakaoScript().then(() => { // Script is fully loaded, now initialize or use Kakao APIs if (!Kakao.isInitialized()) { Kakao.init('your-app-api-key'); } // Call other Kakao functions here }).catch(error => { console.error('Failed to load Kakao SDK:', error); }); } private loadKakaoScript(): Promise<void> { return new Promise((resolve, reject) => { const scriptElement = document.createElement('script'); scriptElement.src = 'http://developers.kakao.com/sdk/js/kakao.min.js'; scriptElement.onload = () => resolve(); scriptElement.onerror = () => reject(new Error('Kakao SDK load failed')); document.body.appendChild(scriptElement); }); } }
This method is perfect if you only need the Kakao SDK in specific components, as it avoids loading the script on every page.
As a bonus, if you want better TypeScript type support, you can check if there's an official or community-maintained type definition for the Kakao SDK on npm (search for @types/kakao-js-sdk). If one exists, install it, and you won't need the declare let Kakao: any; statement anymore—you'll get proper type hints.
内容的提问来源于stack exchange,提问作者Ji Hyeong Kim

