Angular 2+如何在TS组件中导入无export的非模块类库
Got it, let's work through this. Your library is wrapped in an IIFE (Immediately Invoked Function Expression) that attaches the MyFunction constructor to the global browser scope (specifically the window object) since it doesn't use ES module syntax. Here's how you can access it in your Angular component:
Step 1: Load the Library in Your Angular Project
First, make sure your library script is loaded before your Angular app runs. You have two main options:
Option 1: Add to
angular.json
Open your project'sangular.jsonfile, find thescriptsarray underprojects -> [your-project-name] -> architect -> build -> options, and add the path to your library file:"scripts": [ "src/assets/your-library-file.js" ]This ensures the script is bundled and loaded with your app.
Option 2: Add a
<script>tag toindex.html
In your project'ssrc/index.html, add a script tag pointing to your library (place it before the closing</body>tag for best practice):<script src="assets/your-library-file.js"></script>
Step 2: Declare the Global Variable for TypeScript
TypeScript doesn't know about the globally available MyFunction by default, so you need to declare it to avoid compilation errors. You have a couple of ways to do this:
Quick and Simple (Loose Type Checking)
Add this declaration at the top of your component.ts file, before the component decorator:
declare var MyFunction: any;
Better Type Support
If you want TypeScript to provide type hints and catch errors, define an interface for the instance and declare the constructor type:
// Define the shape of your MyFunction instance interface MyFunctionInstance { bar(): void; } // Declare the constructor type declare var MyFunction: { new(): MyFunctionInstance; };
Step 3: Use the Library in Your Component
Now you can create an instance of MyFunction and call its methods just like you would with any other class:
import { Component, OnInit } from '@angular/core'; // Add your declaration here declare var MyFunction: any; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { ngOnInit(): void { // Create an instance of MyFunction const myInstance = new MyFunction(); // Call the bar method myInstance.bar(); } }
Why This Works
Your IIFE executes when the script loads, which assigns the MyFunction constructor to the global window object. By declaring the variable in TypeScript, you're telling the compiler "this exists globally, so don't throw an error when I use it."
内容的提问来源于stack exchange,提问作者ChrisBurns

