Use class imported from a module in multiple subfiles - javascript

I'm currently rewriting a project of mine using ecmascript 2015.
I have a module.js file in which I have two classes. I would like to use those classes in two files (index.php and page.php which is a dynamic generated page included in index.php).
My treefile looks like this:
/..
modules.js // Where I store my classes
page.php // This also contains a <script> part in which I would like to use my classes
index.php // Where I import my .js files
script.js // Where I would also like to use my classes
I have imported my classes in the index.php file like this:
<script type="module" src="js/modules.js">
import * from "./js/modules.js"
</script>
<script src="script.js"></script>
And my module file looks like this:
export { Blabla1 , Blabla2 };
class Blabla1 {
constructor(......) {
.....
}
class Blabla2 {
constructor(......) {
.....
}
}
The problem is that I can't initiate any of the class I've imported in script.js and page.php and get stuck with:
ReferenceError: Blabla1 is not defined
If anyone has any guess on my problem I would really appreciate

Ideally this should work:
<script type="module">
import { Blabla1, Blabla2 } from './js/module.js';
var bla1 = new Blabla1();
</script>`
export { Blabla1 , Blabla2 };
class Blabla1 {
constructor() {
console.log('In Blabla1');
}
} // It's missing
class Blabla2 {
constructor() {
console.log('In Blabla2');
}
}

If you want export/import a class from one.js file to another.js file you should use this code below.
export class Person {
static logme() {
console.log('Hi');
}
}
And then call it from another.js file
import Person from './another.js';
console.log(Person.test());

Related

How do I create a function library which I can used across all my Vuejs components?

I currently writing a financial application using Vue.js and Vuetify. I have a few component files and javascript files like
Dashboard.vue
Cashflow.vue
NetWorth.vue
stores.js <- Vue Vuex
I have some functions which I need to use across all the Vue.js and javascript files. Would it be possible for me to perhaps write a function library which can be used across all
the component and js files.
function moneyFormat(num)
function IRRCalc(Cashflow)
function TimeValueMoneyCalc(I,N,PV,FV,PMT)
function PerpetualAnnuityCalc(I,PV)
function CarLoanInstallment(V,N)
function HouseLoanInstallment(V,N)
I know in C it is very simple just #include<financial.h> was wondering is there something similar in javascript.
Thanks.
There are 3 ways to do this:
1/You can create a helper.js file and import it to .vue files
// helper.js
export default {
function moneyFormat(num) { // some logic}
}
// Dashboard.vue
<script>
import helper from "helper.js" //the path may change depends on where you put the js file
methods: {
useHelper(value) {
helper.moneyFormat(value)
}
}
</script>
2/Another way is bind the function to Vue prototype
in main.js
Vue.prototype.$moneyFormat= function moneyFormat(num) {}
then in Dashboard.vue just call this.$moneyFormat(num). No need to import anything
3/ Use mixins. You can search online on how to use this https://v2.vuejs.org/v2/guide/mixins.html
You can create a single JS file that holds all the helper/util methods, and then export them individually:
export function moneyFormat(num) { ... }
export function IRRCalc(Cashflow) { ... }
export function TimeValueMoneyCalc(I,N,PV,FV,PMT) { ... }
export function PerpetualAnnuityCalc(I,PV) { ... }
export function CarLoanInstallment(V,N) { ... }
export function HouseLoanInstallment(V,N) { ... }
Then, you can simply import individual methods as of when needed, i.e.:
import { CarLoanInstallment, HouseLoanInstallment } from '/path/to/helper/file';
This can be quite usefuly for tree-shaking when you're bundling with webpack, for example, so that you don't bundle unnecessary functions that are never used in your project.
You can use Mixin
In your main.js, add Vue.mixin:
import Vue from "vue";
import App from "./App.vue";
Vue.mixin({
methods: {
helloWorld() {
alert("Hello world");
}
}
});
new Vue({
render: h => h(App)
}).$mount("#app");
and then you can call helloWorld() method from your component script with this.helloWorld() or just helloWorld() from the template.
You also can use filters if the method is to apply common text formatting
In your main.js, add Vue.filter:
import Vue from "vue";
import App from "./App.vue";
Vue.filter("capitalize", function(value) {
if (!value) return "";
value = value.toString();
return value.charAt(0).toUpperCase() + value.slice(1);
});
new Vue({
render: h => h(App)
}).$mount("#app");
and then you can do {{ "some text" | capitalize }} to apply capitalize filter on "some text"
Example here: https://codesandbox.io/s/heuristic-dirac-esb45?file=/src/main.js:0-226

Imported function from js file, doesn't run in TS file

I'm trying to call a JS function inside a component in my TS file, but I'm getting an exception.
Component
import '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {
constructor() {}
ngOnInit() {
var r = new GanttMaster();
}
}
Error:
Error referecences error: GanttMaster is not defined
You need to change the way you import the .js file:
import * as gantt from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {
constructor() {}
ngOnInit() {
var r = new gantt.GanttMaster();
}
}
If you want to use GanttMaster among several components, you can import the .js file in angular.json and declare a constant in app.module.ts like declare const GanttMaster: any. Then you can use it in your application.
Hope this helps.
UPDATE
Alternatively, you can import it the way you've already done, but declare the function manually before the import:
declare const GanttMaster: any;
import from '../../../assets/js/gantt/ganttMaster.js';
export class TaskComponent implements OnInit {
constructor() {}
ngOnInit() {
var r = new GanttMaster();
}
}
Ref: https://stackoverflow.com/a/37084553/1331040
In my project i load a js file from assets, something like this:
add this JavaScript file in scripts array in angular.json file like as above you have added jquery library.
"scripts": [
.....
"src/assets/js/custom.js"
]
custom.js:
function myTest() {
alert('Welcome to custom js');
}
You need declare in your component
declare const myTest: any;

Exporting JS IIFE library to React Component

I'm just starting to learn React JS. So I have this 2 JS files:
Polyfill.js -> github
CustomNavbar.js -> mine
polyfill.js structure
export default (function(window){
...
var classy = {
...
}
...
})(window);
!window.addEventListener && window.Element && (function () {
...
---code---
...
})();
this is customnavbar.js
import { cs } from "./polyfill";
(function(){
...
function openNav(){
...
cs.classy.add(overlay, 'on-overlay');
...
}
...
})();
this is my component.jsx
import "./customnavbar.js"
...
...
it didn't work, the error said that cs is not defined. Maybe I did wrong with the export syntax?
<script src="./polyfill.js">
<script src="./customnavbar.js">
^ i want it to work just like pure HTML, but I don't know how to do it in react. please help!
import "./customnavbar.js"
is not valid syntax for module imports.
Set type of <script> element to "module"
<script src="./polyfill.js" type="module">
return the classy object from the IIFE
"script.js"
export default (() => { const classy = {fn() { return 1 }}; return classy })();
import the exported `classy object
"polyfill.js"
import classy from "./script.js";
// do stuff
plnkr http://plnkr.co/edit/Q0orq8Bvk6nOT8tX0qLg?p=preview

How to import functions from different js file in a Vue+webpack+vue-loader project

I have App.vue which has a template:
<template>
<div id="app">
<login v-if="isTokenAvailable()"></login>
</div>
</template>
I've declared the isTokenAvailable method in the normal way for Vue inside methods. It uses a function that I wrote in a separate js file:
<script>
import * as mylib from './mylib';
export default {
....
methods:{
isTokenAvailable: () => {
return mylib.myfunc();
}
}
}
</script>
mylib starts like this:
import models from './model/models'
import axois from 'axios'
export default function() {
// functions and constants
}
When I run the project, I get this below warning:
export 'myfunc' (imported as 'mylib') was not found in './mylib'
I gather I'm not importing or declaring a javascript module correctly... but there seem to be so many ways to do it, added with the complexity of the scoping in Vue, I'm not sure what is the right way to do it?
Why this isn't a dupe of: How do I include a JavaScript file in another JavaScript file?
That one doesn't seem to fix the problem, specifically in the context of vuejs.
I have tried this:
<script>
const mylib = require('./mylib');
...
</script>
With the function modified to: exports.myfunc = function()
Should I have some other dependency for this to work? Because I get a different error:
[Vue warn]: Error in render function:
TypeError: mylib.myfunc is not a function
Say I want to import data into a component from src/mylib.js:
var test = {
foo () { console.log('foo') },
bar () { console.log('bar') },
baz () { console.log('baz') }
}
export default test
In my .Vue file I simply imported test from src/mylib.js:
<script>
import test from '#/mylib'
console.log(test.foo())
...
</script>
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
Use require in .vue files
<script>
var mylib = require('./mylib');
export default {
....
Exports in mylib
exports.myfunc = () => {....}
Avoid import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib in a .vue component. However as soon as I use mylib there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
I like the answer of Anacrust, though, by the fact "console.log" is executed twice, I would like to do a small update for src/mylib.js:
let test = {
foo () { return 'foo' },
bar () { return 'bar' },
baz () { return 'baz' }
}
export default test
All other code remains the same...
I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt
1)The Component (.vue file)
//MyComponent.vue file
<template>
<div>
<div>Hello {{name}}</div>
<button #click="function_A">Read Name</button>
<button #click="function_B">Write Name</button>
<button #click="function_C">Reset</button>
<div>{{message}}</div>
</div>
</template>
<script>
import Mylib from "./Mylib"; // <-- import
export default {
name: "MyComponent",
data() {
return {
name: "Bob",
message: "click on the buttons"
};
},
methods: {
function_A() {
Mylib.myfuncA(this); // <---read data
},
function_B() {
Mylib.myfuncB(this); // <---write data
},
function_C() {
Mylib.myfuncC(this); // <---write data
}
}
};
</script>
2)The External js file
//Mylib.js
let exports = {};
// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
that.message =
"you hit ''myfuncA'' function that is located in Mylib.js and data.name = " +
that.name;
};
exports.myfuncB = (that) => {
that.message =
"you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
that.name = "Nassim"; // <-- change name to Nassim
};
exports.myfuncC = (that) => {
that.message =
"you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
that.name = "Bob"; // <-- change name to Bob
};
export default exports;
3)see it in action :
https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue
edit
after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://v2.vuejs.org/v2/guide/mixins.html

how to use a function from another js file in reactjs?

i have a file something.js which has a function:
someFunction: function(arg1, arg2){
//code blocks
}
In my app.js file i want to call this function in the app class. I have imported the something.js file like this import { someFunction } from './something.js';. Now i am trying to use it in a function in the app class
var res = someFunction("abc", 2);
console.log(res);`
i am getting a error Uncaught TypeError: (0 , _something.someFunction) is not a function
Some help would be appreciated.
You need to write it like this:
something.js file -
module.exports = {
A: funtion(){
},
B: funtion(){
}
}
Then import it like this:
import {A} from 'something';
Or use it like this:
something.js file -
export A(){
}
export B(){
}
Then import it like this:
import {A} from 'something';
Read this article: https://danmartensen.svbtle.com/build-better-apps-with-es6-modules
In order to import something, you need to export it from the other module.
For example, you could export class YourComponent extends React.Component in something.js.
Then in the other file you can import { YourComponent } from './something'
You could, for example, in something.js do something like
const MyClass = {
methodName() { return true; }
}
export { MyClass as default } // no semi-colon
Then in the other file you could
import WhateverIWant from 'something';
WhateverIWant.methodName(); // will return true
Edit:
An in-depth explanation with lots of examples is available here.
You could either do: in your something.js file: module.exports = function(){}..
and in your app.js file:
const functionName = require('./path_to_your_file');
Or export somethingFunction = {} and in app.js:
import { somethingFunction } from './path_to_your_file'
Or last: export default somethingFunction = {} and in app.js:
import whateverNameYouChoose from './path_to_your_file'
Let me know if that did the trick! :)
In your something.js file, you can add export someFunction near the bottom of the file. This will then allow you to import that function using the import { someFunction } from './something.js'; you have earlier.

Categories