How to import octokit in browser - javascript

tried to follow an example from this. To import octokit I first pasted the following lines into my html document as stated by adding the following lines:
<script type="module">
import { Octokit } from "https://cdn.skypack.dev/#octokit/core";
</script>
This just resulted in an Uncaught (in promise) ReferenceError: Octokit is not defined. Moving the line in script tags directly into the script.js file above the code just made one of the main functions appear as undefined (it handled a button click that authenticated a google account and then retrieved data from google sheets via the sheets API).
I then tried all this with new html and js files, adding that code directly to the html had the same result but this time adding it to the start of the js file gives a import declarations may only appear at top level of a module script.js:1
Don't really know what to do from here so any help would be appreciated. Did find this though but it just says the issue is fixed?

I think the best solution is to write your script logic in a separate javascript file, and then import that file in your html at the end of body element.
Here is an example of getting your repositories from GitHub:
repos.js
import { Octokit } from "https://cdn.skypack.dev/octokit";
import { config } from "./config.js";
const GIT_KEY = config.API_KEY;
export const octokit = new Octokit({
auth: GIT_KEY,
});
const repo = await octokit.request(
"GET /users/{username}/repos{?type,sort,direction,per_page,page}",
{
username: "your_username",
}
);
console.log(repo);
repos.html:
<body>
...
<script type="module" src="repos.js"></script>
</body>

Related

Elixir Phoenix serve Javascript from /priv/static

I am currently fighting esbuild in my phoenix project. I have a heex template on which I want to use Trumbowyg as a text editor. First I tried to import the javascript file via vendoring it and doing import trumbowyg from '../vendor/trumbowyg.min.js in app.js.
I thought this would work because it did for AlpineJs. But it didn't. It complained about missing jQuery. So I vendored jQuery the same way: import {jQuery, $} from '../vendor/jquery.min.js. But no success. Same error message Uncaught ReferenceError: $ is not defined.
Then I had the idea to fix it via importing the scripts in the template withing <script> tags. SO i just threw the two js files into the /priv/static/assets/ folder. This worked in development with the following tags:
<script type="text/javascript" src={Routes.static_path(#conn, "/assets/jquery.min.js")}></script>
<script type="text/javascript" src={Routes.static_path(#conn, "/assets/trumbowyg.min.js")}></script>
But this stopped working in production (I use the docker deploy method). Then I tried using some kind of Plug.Static implementation but I did not get it to work.
So my question now is: How can I make those scripts load in a production environment? Even better would be to know how to configure esbuild to use deploy the script files correctly. I don't know what to change, because my AlpineJs import is working fine.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
import Alpine from "../vendor/alpine.min"
window.Alpine = Alpine;
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
params: {_csrf_token: csrfToken},
dom: {
onBeforeElUpdated(from, to) {
if (from._x_dataStack) {
window.Alpine.clone(from, to)
}
}
}
})
// Show progress bar on live navigation and form submits
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", info => topbar.show())
window.addEventListener("phx:page-loading-stop", info => topbar.hide())
// connect if there are any LiveViews on the page
liveSocket.connect()
// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket
That's the content of my app.js file. But like I said, adding: import trumbowyg from '../vendor/trumbowyg.min.js or import {jQuery, $} from '../vendor/jquery.min.js gets me errors like Uncaught ReferenceError: $ is not defined and Uncaught ReferenceError: jQuery is not defined.
Every help is appreciated. Thanks in advance.

how to use raw html file in nuxt(vue)?

I want to create a page Jump to the stripe payment page use stripe-samples/firebase-subscription-payments .
so I placed it's html/css/js file(which in the "public" folder) to my nuxt app's /static.
However, since it is for static files only, so vuex and plugins could not be used. Fortunately, the tag in html reads firebase from the url, so it is possible to use firebase.
but can I put raw html/css/js files to nuxt/pages like .vue file?(I tried but couldn't..)
I know the best way is to rewrite the html/js file into vue file, but it was too difficult for me as a beginner(Also, I'm Japanese and I'm not good at English,sorry).
or can I use npm package and module in /static/files ?
I have google it for two days and couldn't resolve it.I really need help,thank you!!
here is my code:
static/public/javascript/app.js
import firebase from firebase;
/*↑ it will be error "Cannot use import statement outside a module".
but in pages/.vue files and plugins/files, it will work...
I also tried "import firebase from '~/plugins/firebase.js'"*/
const STRIPE_PUBLISHABLE_KEY = ....
static/public/index.html
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.6/firebase-functions.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.5/firebase-firestore.js"></script>
↑ it read firebase from url, but I want use firebase module I've installed.
Eventually I rewrote the js / html code to vue. Basically it is completed just by copying the js code to mounted(), but since I could not manipulate the nested template tag with js, I rewrote a part using v-if and v-for.
There are several solutions for this.
To load 3rd party scripts, you can use the following solution: https://stackoverflow.com/a/67535277/8816585
Depending on what you're trying to load, using Nuxt plugins can also be a solution: https://nuxtjs.org/docs/2.x/directory-structure/plugins/
Lastly, here is a solution on how to properly handle Stripe in Nuxt: https://stackoverflow.com/a/67504819/8816585
But static is not a place to put your code in. As told, this is for public stuff like favicons, some free pdf book that you want to share to your visitors or alike.
Didn't use firebase with Nuxt lately but those can still probably help figuring out how to write it in Nuxt, I hope.
you can load the html by render() in your vue-component-file
nuxt.config.js
build: {
extend(config, ctx){
config.resolve.alias['vue'] = 'vue/dist/vue.common';
}
}
in your vue-component-file
<script>
import myHtml from '~/path/to/your/html/my_html.html';
export default{
render(h){
return h({
template: `<main>${myHtml}</main>`
});
}
}
</script>
and the page will be rendered as a component in your vue <router-view/> or <nuxt/>, but make sure there is no <script> tag in your my_html.html, put your js code inside the render() like below
<script>
import myHtml from '~/path/to/your/html/my_html.html';
export default{
render(h){
return h({
template: `<main>${myHtml}</main>`,
created(){
console.log('I have been created!')
},
mounted(){
console.log('I have been mounted!')
},
methods: {
exampleMethod(){
alert('this is an example')
}
}
});
}
}
</script>

Trouble with using an npm package (leaflet addon) in html <script> tag

I am trying to include a leaflet package in my locally hosted website. The idea of the website is to allow the user to query for tweets from the Twitter API (the request is sent fro the HTML page to a NodeJs server running on express) and have these sent back and loaded in the leaflet map using a bounding box to place the marker. Since most tweets don't come with a geotag or bounding box information, I thought the next best thing would be to take the name of the location (e.g. London) stored in the tweet metadata and do a reverse geocoding to get the bounding box from the city/location name. To do this reverse geocoding I thought I would use a leaflet add-on called leaflet-geosearch, since the other common option of using the Google Maps API seem not to be free. I have tried now many ways of importing this package into my project, but all with no luck. The documentation shows that it can be loaded using
// import
import { OpenStreetMapProvider } from 'leaflet-geosearch';
// setup
const provider = new OpenStreetMapProvider();
// search
const results = await provider.search({ query: input.value });
So I tried to load it in this fashion in my HTML code inside of a tag as such:
<script type="module">
import { OpenStreetMapProvider } from 'leaflet-geosearch';
// setup
const provider = new OpenStreetMapProvider();
</script>
But it tells me that I need to add a '/' for a relative pathway. So I tried to load it using a relative path to numerous different scripts in the node_modules/leaflet-geosearch folder:
<script type="module">
import { OpenStreetMapProvider } from './node_modules/leaflet-geosearch/dist/geosearch.js';
// setup
const provider = new OpenStreetMapProvider();
</script>
The above method told me that "'geosearch.js' does not provide an export named 'OpenStreetMapProvider'", so I went back and looked through the files some more and found a file named 'openStreetMapProvider.js' and so tried to load this:
<script type="module">
import { OpenStreetMapProvider } from './node_modules/leaflet-geosearch/lib/providers/openStreetMapProvider.js';
// setup
const provider = new OpenStreetMapProvider();
</script>
But it gave me the same error "... does not provide an export named 'OpenStreetMapProvider'".
I have tried to load it directly into my nodeJS server script,
// import
const OpenStreetMapProvider = require('leaflet-geosearch');
// setup
const provider = new OpenStreetMapProvider();
But when I then try to run the server on a local port it throws the Reference error below.
Does anyone know how I could properly load and use this module in my HTML page? I have seen some answers that say browserify can help in such cases, but if that was really necessary then the ReadME on the package's github page should have mentioned this, so I feel like there must be a more straightforward solution to this.

require in Sapper preload function

I am trying to parse some markdown before a page loads, so I have the following code:
<script context="module">
var markdown = require( "markdown" ).markdown;
export async function preload(page, session) {
var someMakrdown = '# Title'
var html = markdown.toHTML(someMakrdown)
return {post : html}
}
</script>
This fails with a 500 and the message: require is not defined
I have also tried using import in the following way:
<script context="module">
import {markdown} from 'markdown';
export async function preload(page, session) {
var someMakrdown = '# Title'
var html = markdown.toHTML(someMakrdown)
return {post : html}
}
</script>
This also fails with a 500 and the message Error resolving module specifier: util
I have got this to work by moving the code into a [slug].json.js file and calling that from within the preload, but is there a better way to do this?
One of the things that I've enjoyed so far about Svelte is keeping the HTML, CSS and JS together for each component. It just doesn't feel right that I need to call a seperate JS file to create JSON that can then be used.
It appears that the markdown module imports util, making it unsuitable for client-side use. Since preload functions run both server-side and client-side, that's no good. My suggestion would be to use a different library instead (I can recommend marked) and/or raise an issue on the markdown bug tracker.
Just in case someone needs a complete answer, here's how it looks like using marked, as proposed by Rich.
<script context="module">
import marked from 'marked';
let elem = '';
export function preload({ params, query }) {
elem = marked('# Marked in the server or/and browser');
}
</script>
<div>{#html elem}</div>
It'll run in the server and then, for subsequent navigation, in the browser.

What is the reason of a referenceError when trying to use a function from cdn script tag?

I can't use npm, not familiar with the details, currently trying to learn 'redux'. What can be the problem here?
When executing this code, I'm getting a "Uncaught ReferenceError: createStore is not defined
at ind.js:5"
Below you can see the code snippet that I have a problem with:
function playlist(state=[]){
return state;
}
const store = createStore(playlist);
console.log(store.getState());
And I have this script tag in HTML file's head tag:
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>
And the js file's script tag in body's end:
<script type="text/javascript" src="./ind.js"></script>
Ok, I'm sorry my previous answer was unhelpful! As it says in the redux docs you need to import the createStore function before you can use it. That is easily done in Node.js, but without it you need to use the ES6 module. Although support for it is supposedly growing, I've still had plenty of trouble with it. This should be supported in Chrome and Edge. To get this to work on Firefox below version 60, go to about:config and change dom.moduleScripts.enabled to true.
Change your script tag to this:
<script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.0/redux.min.js"></script>
and add this as the first line of your code: import { createStore } from 'redux'

Categories

Resources