Sharing a Javascript helper function across two HTML/Javascript files - Blogger feed callback invocation trips up when using ES6 import
In my on-going Barebones Blogger Blog Feed to HTML Book program, I want to share a common helper function writeBook() between index.html or its associated script.js file and blogbook.html which has inline JavaScript (as of now; may change it to use a separate Javascript file later on).
My initial thoughts were that I should look up the net and follow what seems to be standard practices for such sharing. It was difficult for me to get pages that focused on plain vanilla HTML/CSS/JS projects not using node or other package managers. But I thought I should try out the standard advice that some of the top results for my search gave. As an example, this geeksforgeeks article: How to share code between files in JavaScript ? seemed interesting.
I first tried using ES6 export and import keywords. As I had used it for my learning React activity in the recent past, I am familiar with it though I need to look up examples for syntax. One tripping point in this context was that the import statement in script.js was being flagged as an error (something about import cannot be used outside a module or something like that). If I recall correctly (IFIRC), I first tried renaming script.js to script.mjs but that did not solve the issue. It needed a change in index.html script tag to include 'type="module"'. Now things looked all set (I added export and import for helpers too though IFIRC I needed to use full name of helpers file - helpers.mjs / helpers.js for it to be picked up at runtime. Just using ./helpers was giving a Not Found error at runtime.
But then I ran into an error of handleFeed (the callback function specified in Blogger feed script) not being found/recognized - a reference error, IFIRC. To confirm that handleFeed was accessible in the script.js file I made a call to it outside the script, and that call worked as expected. I tried searching the net for more info. about the issue I was facing but I could not get suitable results. I tried specifying type="module" for blogger feed script tag but that resulted in a CORS error! I decided to drop this import and module stuff which seemed to trip up blogger feed script callback function invocation.
In between, I tried ES5 module.exports and require, which I had used for my recent learning Node Express programming activity. But IFIRC, that tripped up on require not being recognized.
I decided to give up on both ES6 import and ES5 require, and go for the option of using separate script tags for helpers.js (first) and script.js in index.html. That worked (as expected). It may not be a recommended way but I don't want to invest time in figuring out why Blogger feed callback invocation trips up when using ES6 import and type="module".
Comments
Post a Comment