简体   繁体   中英

How can I import and use the functionality of a plain JavaScript file in my Angular 5 (CLI) project

I have searched high and low and tried various solutions for hours, but cannot seem to come right with this issue: I am trying to use a plain JavaScript file with an Angular 5 project, created with the Angular CLI .

I have tried various import methods, I have tried "allowJs": true , I have tried exports and a bunch of other stuff. And to no avail!

Please help me: How can I import and use the functionality of a .js file in my Angular 5 project? Could you please list step for step what to do.

Please Note: It is not a package I could install via npm or something like that. It is an external library that is not available via npm.

UPDATE: I have tried declaring my Xcelcious.Common.js file in my index.html as one normally would do <script type="text/javascript" src="Xcelcious.Common.js"></script> , and I have used import to try and make use of the functionality:

import { Xcelcious } from '../../Xcelcious.Common.js';

declare let Xcelcious: any;

But I get the following error when I compile my project: ERROR in src/app/home/home.component.ts(4,27): error TS6143: Module '../../Xcelcious.Common.js' was resolved to 'C:/Apps/CordovaApps/BoilerplateApp2/ngCordova/src/Xcelcious.Common.js', but '--allowJs' is not set.

I have set "allowJs": true in my tsconfig.jason, but get this error when I compile: ERROR in error TS5055: Cannot write file 'C:/Apps/CordovaApps/BoilerplateApp2/ngCordova/src/Xcelcious.Common.js' because it would overwrite input file. Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files.

This is what my tsconfig.json looks like:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "allowJs":true,
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

This is an example of my Xcelcious.Common.js file:

Xcelcious = {
  ApiURL: "http://localhost:100/api",
  IsMobile: false,
  SimulateMobile: true,
  Camera: {
    PhotoFromLibrary: function (success, fail) {
      if (Xcelcious.IsMobile || Xcelcious.SimulateMobile) {
        navigator.camera.getPicture(success, fail, {
          quality: 100,
          destinationType: Camera.DestinationType.DATA_URL,
          //targetWidth: 1024,
          //targetHeight: 768,
          correctOrientation: true,
          allowEdit: false,
          sourceType: Camera.PictureSourceType.PHOTOLIBRARY
        });
      } else {
        //TODO: Add camera for browser
      }
    },
    PhotoFromCamera: function (success, fail) {
      if (Xcelcious.IsMobile || Xcelcious.SimulateMobile) {
        navigator.camera.getPicture(success, fail, {
          quality: 100,
          destinationType: Camera.DestinationType.DATA_URL,
          //targetWidth: 1024,
          //targetHeight: 768,
          correctOrientation: true,
          allowEdit: false,
          sourceType: Camera.PictureSourceType.CAMERA
        });
      } else {
        //TODO: Add camera for browser
      }
    }
 }

Appreciate the help!

I'm not sure if you are using webpack or systemjs.

Make sure you are getting your .js file link injected into your main index.html page, as you would normally add a js file library to your index.html page.

To use the function(s) from the js file, you do the following, I will use jQuery as an example.

To make use of the $ from jQuery you will add

import { ... } from '...';

declare let $: any;

@Component({ ... })
export class MyClass { ... }

The declare let $: any; at the top allows you to use $ inside that component. This will also avoid any tslint errors as well.

That can be used with other libraries such as momentjs , etc.

EDIT:

So you are using Webpack.

Inside your index.html add the following:

<script src="./path to js/Xcelcious.Common.js"></script>

Inside your component you do not need import { Xcelcious } from '../../Xcelcious.Common.js'; .

Doing the declare let Xcelcious: any; should allow you to access methods of Xcelcious , for example Excelcious.IsMobile .

My solution was quite simple (in hind sight!). It is pretty much what @Wesley Coetzee said in his answer, but had to add the reference to my scripts array in .angular-cli.jason .

So this everything I had to do to make it work (my custom JavaScript file is called test.js ):

  1. In my index.html I had to reference my script <script src="app/test.js">
  2. In my .angular-cli.json I had to reference my script "scripts": ["app/test.js"],
  3. In the component I wished to use the test.js script functionality, I had to add declare let test: any; (directly under my imports )
  4. I could then use the functionality by calling test.alert();

NOTE: In my case I had a simple JavaScript object as my functionality in the script. Example:

test = {
  alert: function () {
    alert('Alert!');
  },
  newAlert: function () {
    alert('New Alert!');
  }
};

To make this approach work, I had to explicitly declare test (point no 3) as my variable ( let ) to access the code in the .js file, as this was the name of my JavaScript object .

In your component you can simply import your plain js file and declare your external object:

import 'external.js'
declare var myExtObject: any;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM