在Ionic 2(TypeScript+Angular 2)中如何引入外部JavaScript文件?
Hey there! Let's walk through how to include and use that external JavaScript file in your project—here are a few reliable methods depending on your needs:
Method 1: Global Inclusion (Simplest for Global Scripts)
If the script exposes global functions/variables you need across your app, add it directly to your index.html file:
- Open your project's
src/index.html - Add the script tag right before the closing
</body>tag (to avoid blocking page load):
<script src="https://xxxxxxxx.in/globaljsfile/sample.js"></script>
Using the Script in TypeScript
Since TypeScript doesn't recognize global variables from external scripts by default, declare them to avoid compilation errors:
// At the top of your component/service file (before the @Component decorator) declare const sampleGlobalFunction: any; declare const sampleGlobalVariable: any; // Then use them anywhere in your code ngOnInit() { sampleGlobalFunction(); console.log(sampleGlobalVariable); }
For better type safety, create a TypeScript declaration file (e.g., src/sample.d.ts) with proper type definitions:
declare function sampleGlobalFunction(param: string): void; declare const sampleGlobalVariable: { key: string; value: number };
TypeScript will automatically pick up this file and give you useful type hints.
Method 2: Dynamic On-Demand Loading
If you only need the script in specific components (and want to avoid loading it globally), load it dynamically in your component:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-my-component', templateUrl: './my-component.html' }) export class MyComponent implements OnInit { ngOnInit() { this.loadExternalScript(); } private loadExternalScript(): void { const script = document.createElement('script'); script.src = 'https://xxxxxxxx.in/globaljsfile/sample.js'; script.type = 'text/javascript'; script.async = true; script.onload = () => { // Script is loaded and ready to use window['sampleGlobalFunction']('Hello from dynamic load!'); }; document.body.appendChild(script); } }
Method 3: Webpack Configuration (For Advanced Cases)
If your script is a module (UMD/CommonJS), configure Webpack to handle it:
- If the script is available via npm, install it first (skip this if it's only accessible via URL)
- Add an external entry in your
webpack.config.js(or Ionic-specificionic.config.json):
module.exports = { // ... other config settings externals: { 'sample-script': 'window.sampleGlobalFunction' } };
Then import and use it in your TypeScript file:
import * as sampleScript from 'sample-script'; // Use the script like this: sampleScript('Test input');
内容的提问来源于stack exchange,提问作者abhimanyu

