Add new JS class and template to aurelia project

258 views Asked by At

I am new to Aurelia, but am working on an existing project and learning as I go. I want to add a javascript class file and have NPM include it in the build, but I cannot find clear documentation on how to do that.

It is not a complex class and does not require an html template.

2

There are 2 answers

0
John Little On

Just add the .js file containing your class to your src folder and add the following to import it in the file you intend to use the class.

import * as MyClass from './my-classs';
0
rkever On

following the convention, you can create a class with the below...

export class MyClass {
    myProperty = 'foo';
    myOtherProperty = { key:'value' };

    constructor() {
        // constructor stuff (optional of course)
    }

    myMethod() {
        // do something
    }
}

Then in your ViewModel, for example...

import { inject } from 'aurelia-framework';
import { MyClass } from 'path/to/my-class';

@inject(MyClass)
export class MyViewModel {
    constructor(myClass){
        this.myClass = myClass;
    }

    attached() {
        console.log(this.myClass.myProperty);
        this.myClass.myMethod();
    }
}

The way you import your class does depend on whether it's written as a module or not. If it's not a module, you'll have to write it out as @john-little mentioned.

The MyClass will automatically be a singleton until you make it transient (see https://aurelia.io/docs/fundamentals/dependency-injection#object-lifetime-child-containers-and-default-behavior)