Import package in javascript file which is script for html - javascript

I am doing electron project. In it every tutorial i have watched is adding js in <script> tag i want to separate the js code from html. So i
...
<script type="text/javascript" src="./../scripts/upload.js" ></script>
...
<input onchange="upload()" id='train-button' type="file">File</input>
....
and in js file i
function upload(){
const electron = require('electron');
const {ipcRenderer} = electron;
if (x.files.length == 0) {
alert("Select one or more files.");
}else{
ipcRenderer.send("saveFile",targetFile,destinationPath)
}
}
Now here i am getting error that
Uncaught ReferenceError: require is not defined
but if i define require outside the upload function then it is not running that line and saying
electron is undefined

Try setting nodeIntegration:true in your BrowserWindow config. Doing so will enable require in your js file.
However, this is very poor security practice. I recommend using a security-focused template.
This post might also help explain to you more about best-practices in electron apps regarding using IPC between renderer/main processes.

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 import octokit in browser

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>

How to load external library from local path

I have a code importing list of external urls(http//....js)
for (const id in urls) {
let tag = document.createElement('script');
tag.async = false;
tag.src = urls[id];
let body = document.getElementsByTagName('body')[0];
body.appendChild(tag);
}
But for security reasons, I copy&pasted the js file to local file, but dont know how to import it like I used to do.
Simply
import "../lib/asmcrypto.js";
gives me thousands of errors saying 'Expected an assignment or function call and instead saw an expression'.
Any help is appreciated!
If you're inside a browser, the most common way of loading your JS resource would be:
<script src="/lib/asmcrypto.js"></script>
If you're using Webpack at some level, like when you're project is on React or Angular or ...
import crypto from "../lib/asmcrypto.js";
It's important to understand that, it's usually the bundler e.g. Webpack that takes care of import and export in your project.

How to import a module from the static using dynamic import of es6?

I'm trying to add dynamic import into my code to have a better performance on the client-side. So I have a webpack config where is bundling js files. On SFCC the bundled files are in the static folder where the path to that files is something like this: /en/v1569517927607/js/app.js)
I have a function where I'm using dynamic import of es6 to call a module when the user clicks on a button. The problem is that when we call for that module, the browser doesn't find it because the path is wrong.
/en/lazyLoad.js net::ERR_ABORTED 404 (Not Found)
This is normal because the file is on /en/v1569517927607/js/lazyLoad.js.
There is a way to get it from the right path? Here is my code.
window.onload = () => {
const lazyAlertBtn = document.querySelector("#lazyLoad");
lazyAlertBtn.addEventListener("click", () => {
import(/* webpackChunkName: "lazyLoad" */ '../modules/lazyLoad').then(module => {
module.lazyLoad();
});
});
};
I had the same problem and solved it using the Merchant Tools > SEO > Dynamic Mapping module in Business Manager.
There you can use a rule like the following to redirect the request to the static folder:
**/*.bundle.js i s,,,,,/js/{0}.bundle.js
All my chunk files are named with the <module>.bundle pattern.
Here you can find more info :
https://documentation.b2c.commercecloud.salesforce.com/DOC1/topic/com.demandware.dochelp/content/b2c_commerce/topics/search_engine_optimization/b2c_dynamic_mappings.html
Hope this helps.
I believe you'll likely need to do some path.resolve() magic in either your import statement or your webpack.config.js file as is shown in the accepted answer to this question: Set correct path to lazy-load component using Webpack - ES6
We did it in a different way. That required two steps
From within the template file add a script tag that creates a global variable for the static path. Something like
// inside .isml template
<script>
// help webpack know about the path of js scripts -> used for lazy loading
window.__staticPath__ = "${URLUtils.httpsStatic('/')}";
</script>
Then you need to instruct webpack to know where to find chunks by changing __webpack_public_path__ at runtime
// somewhere in your main .js file
// eslint-disable-next-line
__webpack_public_path__ = window.__staticPath__ + 'js/';
Optional step:
You might also want to remove code version from your __staticPath__ using replace (at least we had to do that)
__webpack_public_path__ = window.__staticPath__.replace('{YOUR_CODE_VERSION_GOES_HERE}', '') + 'js/';

Correct way to export/define functions in Electron's Renderer

I have a JS file that I'm importing into my Electron's "main" (or background process), app.js, using require (eg: const myJS = require("./pathToMyJS/myJS");)
Contents of myJS.js:
module.exports = {
mFunc: function mFunc(param1) {
...
}
};
And I can use mFunc in app.js as myJS.mFunc(param1); & everything's great.
Then, I tried to follow the same process for the "renderer" JS. So my renderer.js now imports const myOtherJS = require("./myJS/myOtherJS"); where this other JS file follows the exact same module.exports logic as myJS.
And the root HTML (app.html) declares the renderer as <script defer src="./renderer/renderer.js"></script>.
But on launch, I get:
Uncaught TypeError: Cannot set property 'exports' of undefined
at renderer.js? [sm]:34
Searching online, I came across this answer that mentions that the AMD way could be used instead of the commonJS way. So I tried the following: (not sure whether this is syntactically correct!)
define(
["renderer"],
function rFunc(param1) {
... }
)
But that fails with:
Uncaught ReferenceError: define is not defined
So what's the correct way to have functions defined for export when using them in the renderer? What I've been doing so far is just to write the functions in their own JS files (eg: function func1() { ...}) & declaring all of these files in the app.html as <script defer src="./funcFile1.js"></script>.
Turns out, I was just exporting incorrectly. modules.export was the point of failure as modules is undefined on the renderer.
Instead, if I do the following to export individual functions:
// ./myJS/myOtherJS.js
export function rFunc() { ...}
And then import into my renderer.js like:
import { rFunc } from './myJS/myOtherJS';
rFunc();
Things work as I originally expected.
This Google Developers Primer on modules was useful in understanding the concepts.
AMD is not provided by node.js by default. It's used by Require.js and other FWs. Here is a link on how you can use it with node:
https://requirejs.org/docs/node.html

Categories

Resources