Adding external javascript to Ionic 2 project - javascript

Lets say I have this foo.js file where I declared a variable, a function and a class.
It is not in the project yet.
Now assume I want to use this variable, class and function in my home.ts method, or just make it globally available (to use in a home.ts method).
How can I make it happen?

lets say in your foo.ts file we have a funtion
myfunt(){
//your logic goes here
}
now if you want to make use of this function in home.ts file the
step1: import your foo.ts file in home.ts
step2: in your export class should look like this
export class home extends foo {
//since you have used extends keyword now you unlocked all the data in foo.ts file for home.ts file
//here now try to access your myfunt() funtion
constructor(){
super.myfunt(); //user super keyword to access all the data available in foo.ts file
}
}

You can use definition files (.d.ts).
First, check if foo.js have already a definition file created by the community. Check it here:
http://microsoft.github.io/TypeSearch/
or here https://github.com/DefinitelyTyped/DefinitelyTyped
If it exists you can install it like this:
npm install --save #types/foo
If not, you can create your own definition file for this javascript file.
Let call it foo.d.ts with a content like this:
declare var data:any;
declare function myFunc(n:string);
Once you have it you can use it like a normal ".ts" file.
import * as foo from "./foo"; //"./foo" is the path of your .d.ts.
foo.myFunc()
More information here:
https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/

Related

Laravel Vite Can't Use JS Functions Globally

I'm using Laravel with Vite. But I'm having a trouble. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
I have an app.js file looks like this:
import jQuery from 'jquery';
window.$ = jQuery;
import './bootstrap';
import './main.js';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
And I have a function like this in main.js:
function testFunction() {
alert('test');
}
I put Vite definitions to my layout blade like this:
#vite(['resources/css/app.css', 'resources/js/app.js'])
I have another page contains another JS file like this:
#extends('layouts.app')
#section('content')
#endsection
#section('scripts')
#vite(['resources/js/edit-note-page.js'])
#endsection
And in that JS file I want to use the function that I mentioned in the beginning like this:
testFunction();
But I'm getting an Uncaught ReferenceError: testFunction is not defined error in console. I couldn't figure it out. What is the correct way to do it?
I'm using Laravel with Vite. I have multiple JS files and including them whenever I want to use. But I cannot use the function I created in one file in another file.
Each file is going to be wrapped to actually prevent what you are attempting to do, unless explicitly defined on the window object (notice how window.Alpine = Alpine; is set in your app.js). An alternative and more modern way is to use exports. Here is an example using your file structure.
main.js:
function testFunction() {
alert('test');
}
export default testFunction;
edit-note-page.js:
import testFunction from './path/to/file/name';
...code here
The path to the file in the import does not need the extension .js at the end.
Note: After this change, you no longer need import './main.js'; inside of app.js

Referencing vanilla js file in TypeScript getting file is not a module

I'm trying to import a file into TypeScript that's basically just a js file that you'd put into a tag. I've tried a few different things.
// global.d.ts
declare module 'myfile.js'
Inside of the react file:
// component.tsx
import { foo } from '../lib/myFile.js' // This is saying it is not a module
Inside of the js file, it looks like this a few times so not sure how I need to reference the file:
(function( something ) {
something.Foo = function (){}
}(window.something = window.something || {}));
Any thoughts on how I could use this file? Do I need to go through and declare typings for everything in it?
EDIT: I've added allowJS to my tsconfig but it still doesn't work.
You can only import what is exported from the file.
If your file contains only immediately invoked functions, or top level code, you only need to import the file itself like this:
import '../lib/myFile.js'
This is a little weird, however. I would suggest wrapping everything with a function and exporting then importing that function instead.

Import external js File in Angular 4 and access functions and variables

Maybe my title is a bit unclear, so I will try to explain my problem with a simple task.
Lets say I have a the following Javascript File "file.js":
var number = 4;
function encode(){
console.log("encode in "file.js" has been called...");
}
I place this script in my angular4 project in "src/assets/js/file.js".
In ".angular-cli.json" I add the path of the script
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"./assets/js/modernizr.js",
"./assets/js/webflow.js",
"./assets/js/file.js"
Now my question is how can import or use this script file in my app.module.ts or any other component, without adding it to index.html
I tried several ways:
import * as test from 'assets/js/file.js';
import {test} from 'assets/js/file.js';
declare var file: any;
Unfortunately, none worked...
I would really appreciated it, if you guys could help me out.
You can use system.js to import file at runtime as below, you have to add systemjs in node_modules.
System.import("src/assets/js/file.js").then(fileInstance => {
console.log(fileInstance);
});
In component.ts you should declare the name of the function you want to use.
declare let encode:any
ngOnInit(){
encode()
}
You can Import js locally to ts file like this : import '../../../scripts/custom.js';
then declare method name in custom.js that you want to use like this 👍
declare var fAlert;
then in a place like ngOnInit directly use this method
fAlert();

Invoke JQuery method from Angular 2 component

I'm working on creating an Angular 2 front end on an existing project that previously just used JQuery. Is it possible to invoke a JQuery method inside of an Angular 2 component, when that JQuery function exists in a separate file? I'm writing my components in TypeScript, in case that is important to know.
For example, I have a JavaScript file called EditCheckBoxes.js with a method called editCheckBoxes(). In order for editCheckBoxes() to work, I need it to be invoked after a certain component is initiated. My attempted solution was this:
ngOnInit(): void {
editCheckBoxes();
}
This code gives me the following error:
Cannot find name 'editCheckBoxes'.
Is there any way I can get this to work?
Also, I added declare var $: any; to my component file, so I am able to use JQuery within that component, but I'd rather not copy entire files into my components in order to use them.
EDIT:
The folder structure looks like this:
Plan
app
selling
My Angular 2 component
Scripts
EditCheckBoxes.js
In my component, the import statment looks like this: import { editCheckboxes } from '../../Scripts/EditCheckboxes';
You need to import the editCheckboxes method in your typescript file for it to be available.
To do that you first need to export the editCheckboxes function from EditCheckBoxes.js
export function editCheckboxes() { ... }
Next you should just import that function inside your component
import { editCheckBoxes } from './EditCheckBoxes';
Now it can be called in your component: editCheckBoxes();
In order to import function from js file you should at first export it like so:
// EditCheckBoxes.js
module.exports = function editCheckBoxes () { ... };
then add a d.ts file in same directory as your js-file with definition of your module that would be used by Typescript
// EditCheckBoxes.d.ts
declare function editCheckBoxes (): void;
export = editCheckBoxes;
then in your Typescript file you would specify your definition file, import your function and use it like so:
/// <reference path="../../Scripts/EditCheckBoxes.d.ts" />
import editCheckBoxes = require('../../Scripts/EditCheckBoxes');
ngOnInit (): void {
editCheckBoxes();
}

Can I create definition file for local JavaScript module?

Let's say I have a a.js file that contains:
export function a() {}
and I want it to import it from the file b.ts (in the same directory) like that:
import { a } from './a.js'
How can I tell TypeScript what the file a.js contains so that compilation of this import succeeds?
What is needed for this to work is typescript definition file named same as JavaScript file (a.d.ts in this case) that contains:
export function a();
It can also specify parameter types, additional exported functions and classes and must use export keyword to indicate what the JavaScript file actually exposes.
One other change is that this JavaScript module needs to be then imported in b.ts as:
import { a } from './a' // without .js
so it takes typescript definition file into account. It will still use implementation from a.js file. It works with webpack too.
If you don't want to describe what's inside a.js and have TypeScript just accept it you can create a.d.ts file like that:
declare var whateva:any;
export = whateva;
Then you can import it like this:
import * as ajs from './a'
and then refer to any function exposed by a.js in your TypeScript files like that:
ajs.a();
You can just simply use a statement:
declare var a:any;
(after the import) in this same file you are using the a (i this case in b.ts). Thanks to this the TS compiler will not complain. Also your IDE will not shown the errors.

Categories