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 {localStorageServi...

问题:

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("john@gmail.com");
    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.


回答1:

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. :)

  • 发表于 2019-07-08 00:26
  • 阅读 ( 270 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除