John S.
John S.

Reputation: 514

Trying to include a simple module - can't get it to work Pure Javascript

I am trying to include a simple module I made, and it is not working.

From my index.html page, I am including this file:

login-view-model.js

import {localStorageService} from '../shared/local-storage-module.js';

// Login View Model

var LoginViewModel = function () {

    self = this;
    this.token = ko.observable();

    this.email = ko.observable("[email protected]");
    this.password = ko.observable("12345");

    self.submit = function() {
        (async () => {
            const rawResponse = await fetch('http://localhost/chitra-admin/api/user/', {
              method: 'POST',
              mode: 'cors',
              headers: {
                'Accept': 'application/json',
              },
              body: JSON.stringify({email: self.email(), password: self.password()})
            });

            const content = await rawResponse.json();

            if(content.response.id){
                self.token(content.response.token);
                localStorageService.save('token', self.token());
                alert(sessionStorage.getItem('token'));
            }

            console.log(content.request.token);

          })(); 
    }

}; // End View Model


// Helper Functions For Fetching Data
function handleErrors(response) {
    if (!response.ok) {
        console.log(JSON.stringify(response));
        throw Error(response.statusText);
    }
    return response;
}



ko.applyBindings(new LoginViewModel());

And I am getting this error:

Uncaught SyntaxError: Unexpected token {

I can't see where I am going wrong. My local-storage-module.js is about as simple as you can get:


const localStorageService = {

    save: function(key, val){
        sessionStorage.setItem(key, val);
    }

}



export {localStorageService} ;

I know the function is not practical, but I am learning. I eventually will include more complex modules, but I can't even get this simple one to work.

Any ideas?

Thanks.

Upvotes: 1

Views: 35

Answers (1)

SimoMatavulj
SimoMatavulj

Reputation: 594

Do this :

In local-storage-module.js instead of export {localStorageService} ; add module.exports = localStorageService and in login-view-model.js do const localStorageService = require('../shared/local-storage-module.js')

It is a bit old school but it will work in pure JS. :)

Upvotes: 2

Related Questions