How to Import Third-Party JavaScript in Angular Projects
·
2 min read
In actual Angular project development, you may need to import third-party JavaScript libraries, such as base64.js, a base64 encoder.
How do we do this?
Importing the JS Library
npm install --save js-base64
Installing Type Declaration Files
npm install --save-dev @types/js-base64
Importing in Components
import {Base64} from 'js-base64';
export class HomeComponent implements OnInit {
constructor() {
console.log(Base64.encode('dankogai'));
}
...
}
As shown above, you can use js-base64 normally. It’s not difficult, but there are a few points to clarify.
What are @types?
- TypeScript is a superset of JavaScript. Compared to JavaScript, its most critical feature is static type checking (Type Guard). However, JavaScript itself doesn’t have static type checking functionality, and the TypeScript compiler only provides type declarations for standard libraries in the ECMAScript standard, and can only recognize types in TypeScript code.
- TypeScript declaration files are TypeScript code files with a .d.ts suffix, but their purpose is to describe type information for all exported interfaces in a JavaScript module (in the broad sense).
- The @types package we install here is the declaration file for js-base64. It’s precisely because of this that the js-base64 object type can be recognized, and we can see that the IDE recognizes its functions like encode().
Where does js-base64 go after import and bundling?
With this import method, during build and bundling, js-base64 will be included in the ng project files. If the system doesn’t use lazy loading, it will be in main.js. If lazy loading is implemented, it will be included in the corresponding chunk.js file of the module that imports and uses it.
Is the @types approach the only solution?
NO! We can also do this:
- Import the corresponding JS resource in the index.html file
- Declare at the top of the component that uses it:
declare const Base64: any;
This also works, but the downside is that it doesn’t leverage TypeScript’s static type checking, so there are pros and cons.