Home > Enterprise >  Import javascript from node_modules in angular
Import javascript from node_modules in angular

Time:08-25

I installed a npm package which contains a javascript file, what I want to use. The js file name is all.js and contains this code:

import { initExtended } from './extended'
import Header from './components/header/header'

function initAll(options) {
  // Set the options to an empty object by default if no options are passed.
  options = typeof options !== 'undefined' ? options : {}

  // Allow the user to initialise GOV.UK Frontend in only certain sections of the page
  // Defaults to the entire document if nothing is set.
  var scope = typeof options.scope !== 'undefined' ? options.scope : document
  
  // Find first header module to enhance.
  var $toggleButton = scope.querySelector('[data-module="govuk-header"]')
  new Header($toggleButton).init()

  initExtended(options)
}

export {
  initAll,
  Header
}

File all.js is located in node_modules.

When I tried to import it directly from index.html like:

<script type="module" src="node_modules/@id-sk/frontend/govuk/all.js"></script>

It is not working. Console error, file not found.

I also tried import it via angular.json:

"scripts": [
   "./node_modules/@id-sk/frontend/govuk/all.js"
]

Also not working with error "Uncaught SyntaxError: Cannot use import statement outside a module (at scripts.js:15241:1)". The error refers to line:

import { initExtended } from './extended'

I also tried to import it in polyfills but I don't know how to call it.

CodePudding user response:

As you are speaking about angular.json, I assume that you are working in an Angular application bootstrapped using the Angular CLI with default settings.

To be able to use this package @id-sk/frontend in your typescript files, you have to import it directly into your typescript file.

1. Import @id-sk/frontend in your TS files

// Import everything into a local variable
import * as govuk from '@id-sk/frontend';
// Import specific object
import { HeaderExtended } from  '@id-sk/frontend';

2. Run ng serve

Spoil: It will lead to typings errors

3. Let's add or create typings

As @id-sk/frontend is not written in typescript, the compile doesn't know about the typings of this library. Following this statement, you have two choices:

  • Find or contribute to DefinitelyTyped in order to create the typings of your package @id-sk/frontend

  • Create a local file typings.d.ts in your ./src folder to declare an empty module

declare module "@id-sk/frontend"

4. Kill & run ng serve again

Enjoy it!


Go further

You can add typings to your module in order to give you autocompletion on the provided objects of @id-sk/frontend.

``ts declare module "@id-sk/frontend" {

export interface Options {
    scope?: Document
}

export function initAll(options: Options): void;    

}

  • Related