1

I am trying to figure out how to import JavaScript files ONLY to a specific component.

I put the following code directly into my component:

import "../../vendor/datatables/js/jquery.dataTables.min.js";
import "../../vendor/datatables-plugins/dataTables.bootstrap.min.js";
import "../../vendor/datatables-responsive/dataTables.responsive.js";

But it fires an error saying:

Module not found: Error: Can't resolve 'jquery' in...

Which makes me suspect that the files that depend on jQuery cannot find the jQuery library in this scope.

jQuery itself is put in the angular-cli.json file:

"scripts": [
    "./vendor/jquery/jquery.min.js"
],

An alternative is to put all of those 3 external JS files into the angular-cli.json file as well, and it will work, showing the expected result from the user perspective.

But I would like to figure out how to avoid setting the JS globally for those that are used only in a few specific components.

Thanks, please advise.

2
  • have you installed files using npm? Commented Sep 29, 2017 at 2:37
  • Hi brk, for the jquery, I would like to use an external file which I downloaded myself instead from the npm install. Commented Sep 29, 2017 at 2:38

1 Answer 1

2

For example, to import jQuery to your component, you should write:

import * as $ from 'jquery';

Which means "Import all and use as "$" from "jQuery"".

If you downloaded the library by yourself, without npm install, you can try the following (but I'm not sure that it will work):

import * as $ from 'path/to/jquery';
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works, though I need to set the AllowJs to true in tsconfig.json
@Zan, nice to hear, that it help you. Cheers

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.