[SOLVED] Use `import` in framework7

Hello,
I have a simple question. I have a JS class in a separate folder, it has lots of functions I wanna use.

I am trying to include the script using something like

import GoogleMapsApi from './GoogleMapsApi/GoogleMapsApi.js';on top of my app.js but i keep getting an error in the console. I tried to import from the components themselves, and the same thing happened:

import GoogleMapsApi from './LoadGoogleMaps/GoogleMapsApi.js';

// Init App
var app = new Framework7({

  root: '#app',

  data: function () {
    return {
      LoadGoogleAPI: {
        CLASS_OBJECT: new GoogleMapsApi();
      },
    };
  },
});

On my component, I try to use the class by,

const gmapApi = self.$root.LoadGoogleAPI.CLASS_OBJECT;

A white page and console errors are all I get… How can I go about it?
Thanks in advance.

Console Error: app.js:10 Uncaught SyntaxError: Unexpected identifier (on line of import)

@nolimits4web, @pvtallulah

you are using webpack. right?

@pvtallulah, nice… thanks alot bro.

No, I wasn’t using webpack… I just wrote my simple class and tried to import it into the app… Normal vanilla F7, I should say…

1 Like

so its solved? (min 20 chars)

No… not really @pvtallulah… I was happy that you attended to my problem which is why I got excited and thanked you and I meant that I didn’t use webpack or any dependencies… I used plain f7, so the issue is still alive and so strong…:slightly_smiling_face:

ok, why not add the js file with a script tag in index.html?
i did that from my project with recaptcha

<script src='https://www.google.com/recaptcha/api.js'></script>
1 Like

Actually, I was thinking of that…including it as a separate file… so you mean I can’t simply use ‘import’ without webpack? I thought I could write any Js my way…because F7 is Js too

You can give this a try
never done it. i like webpack.

@pvtallulah… Thanks a lot !! I really appreciate… Let me try it out… qill obviously mark this as solved right after…

@pvtallulah, I later decided to include my class into the file itself… But there is an issue, everything seems to load and work well but I can barely see any suggestions from google. We later decided to use google autocomplete API. I test the code on a separate file (not in F7), everything works well but on doing so inside my app (F7), I can barely see a thing…

my APP.JS

// Dom7
var $ = Dom7;

// Theme
var theme = 'auto';
if (document.location.search.indexOf('theme=') >= 0) {
  theme = document.location.search.split('theme=')[1].split('&')[0];
}

class GoogleMapsApi {
  /**
   * Constructor set up config.
   */
  constructor() {
    // api key for google maps
    this.apiKey = 'API_KEY';

    // set a globally scoped callback if it doesn't already exist
    if (!window._GoogleMapsApi) {
      this.callbackName = '_GoogleMapsApi.APILoaded';
      window._GoogleMapsApi = this;
      window._GoogleMapsApi.APILoaded = this.APILoaded.bind(this);
    }
  }

  /**
   * Load the Google Maps API javascript
   */
  load() {
    if (!this.promise) {
      this.promise = new Promise(resolve => {
        this.resolve = resolve;
        if (typeof window.google === 'undefined') {
          const script = document.createElement('script');
          script.src = `https://maps.googleapis.com/maps/api/js?key=${this.apiKey}&libraries=places&callback=${this.callbackName}`;
          script.async = true;
          document.body.append(script);
        } else {
          this.resolve();
        }
      });
    }

    return this.promise;
  }

  /**
   * Globally scoped callback for the map loaded
   */
  APILoaded() {
    if (this.resolve) {
      this.resolve();
    }
  }
}

// Init App
var app = new Framework7({
  id: 'io.framework7.testapp',
  root: '#app',
  theme: theme,
  actions: {
    backdrop: false,
  },
  data: function () {
    return {
      LoadGoogleAPI: {
        CLASS_OBJECT: new GoogleMapsApi(),
      },
    };
  },
  dialog: {
    color: 'red'
  },
  view: {
    pushState: false,
    animate: true,
    mdSwipeBackAnimateShadow: false,
    stackPages: true
  },
  methods: {

  },
  routes: routes,
  vi: {
    placementId: 'pltd4o7ibb9rc653x14',
  },
});

app.views.create('.view-main', {
  url: '/'
});

so, On my component:, I use it like:

 GoogleAutocomplete: function(){

  const gmapApi = self.$root.LoadGoogleAPI.CLASS_OBJECT;

    gmapApi.load().then(() => {
    var input = document.getElementById('pac-input');
     var autocomplete = new google.maps.places.Autocomplete(input);
       autocomplete.setTypes([]);
      autocomplete.setFields(['address_components', 'geometry', 'name']);
      autocomplete.setComponentRestrictions({'country': ['ug']});

       autocomplete.addListener('place_changed', function() {
   
          var place = autocomplete.getPlace();
           if (!place.geometry) {
          app.dialog.alert("Invalid Address: '" + place.name + "'");
               return;
            }
           else{

             var myLocation = String(place.geometry.location);
            var resulta = myLocation.slice(1,-1);
            var myLatLongArray = resulta.split(",");
          
              var Lat = myLatLongArray[0];
             var Lng = myLatLongArray[1];

                 input.val() = place.name;//input box

              /*Logic*/   
           } 
           });
   });
 },

On pageInit(), i simply call the function like: self.GoogleAutocomplete();
I get no errors in the console, my test script works very well… I just dont know why I cant see any predictions when i type…

<template>
<div class="page manual-locs-page" data-name="found-doc-info">
 <div class="navbar">
      <div class="navbar-inner sliding">
       <div class="left">
            <a href="#" class="link back">
              <i class="icon icon-back"></i>
              <span class="ios-only">Back</span>
            </a>
          </div>
        <div class="title"><strong>Choose Your Address</strong></div>
      </div>
  </div>
<div class="page-content">
    <div class="card card-outline">
    <div class="card-header card-header-style"><strong>Alright, Tell Us Your Address...</strong></div>
    <div class="card-content">
      <div class="list no-hairlines-md">
      <ul>
          <li class="item-content item-input">
            <div class="item-inner">
              <div class="item-input-wrap">
                <input type="text" id="pac-input" class="text-color-black no-fastclick" placeholder="Where Are You Located?"/>
              </div>
          </div>
         </li> 
      </ul>
    </div>
    </div>
  </div>

  
    {{#if TurnRestOfPageVisible}}
    <div class="block">
      <div class="row">
         <button class="col button button-fill button-raised proceed-btn" @click="ShowOtherCOntent"><strong>CONFIRM PLACE</strong></button>
       </div>
    </div>
    {{/if}}
  
  {{#if showTheRestOfThePage}}
    <div class="card card-outline">
        <div class="card-content card-content-padding">
          <table>
            <tr><td><strong class="text-color-black">Address: </strong></td><td><strong class="text-color-blue" id="address-value">{{address_chosen}}</strong></td></tr>
          </table>
        </div>
    </div>
                
    <div class="block">
      <div class="row">
         <button class="col button button-fill button-raised proceed-btn" @click="chooseLocation"><strong>PROCEED WITH REGISTRATION</strong></button>
       </div>
    </div>  
 {{/if}}
</div>
</div>
</template> 

There are several DOM control methods but just that’s how my template looks like… I am guessing it is a CSS problem maybe…
I can create a fiddle and send you the key privately… I am thinking it is a CSS problem…maybe

If you are going to support old Android, iOS or IE then you shouldn’t use Classes, Imports and Promises without transpiling them to ES5 code

1 Like