How to make Javascript code run in Phoenix? - javascript

So I am having a hard time making Javascript written in app.js actually work. This is what I have done so far:
First thing I did was write the code into the app.js file and hope it would work.
App.js
import "deps/phoenix_html/web/static/js/phoenix_html"
const selectSort = document.getElementById("sort");
console.log("Herp");
const sortEntities = () => {
const sortvalue = selectSort.value;
const entities = document.querySelectorAll(".entitiy");
const sortedEntities = entities.sort((a, b) =>
a.querySelector(`.${sortvalue}`).textContent > a.querySelector(`.${sortvalue}`).textContent);
document.querySelector(".entitiy-list").innerHTML = sortedEntities;
};
selectSort.addEventListener("onChange", sortEntities);
Now I tried accessing the selectSort variable through console but I get undefined. I discovered that the app.js is never loaded in since I run windows and it could be fixed by adding another line in the autoRequire.
brunch-config.js
<---SNIPPET-->
modules: {
autoRequire: {
"js/app.js": ["web/static/js/app"],
"js\\app.js": ["web/static/js/app"] <-- The line added
}
},
<---SNIPPET-->
Now that the app.js file finally loads properly I get an error with the phoenix_html import.
Error
Uncaught Error: Cannot find module "deps/phoenix_html/web/static/js/phoenix_html" from "web/static/js/app"
Even if I remove the import the variable will still not load properly when i type it into the console and the code never executes, while console.log message is executed. What am I missing? If I try write the code in the console window it works fine.
The project itself is quite old, probably from like November, so i might not be running the newest "phoenix template". Not sure if there are some known issue to this related there, i tried looking around. I even have "Programming Phoenix" but there wasn't much about making Javascript run there.

My project used Phoenix 1.0 which had known issues with Windows and making Javascript execute properly. I upgraded to 1.1.2 and now everything works fine.

Related

Module not found when requiring library submodule in Jest tests

I am currently trying to write some tests for a node-based GCP Cloud Functions application.
At this point I've stripped it down to the bare minimum:
// index.js
const functions = require("#google-cloud/functions-framework");
const testing = require('#google-cloud/functions-framework/testing');
functions.http("updateProvider",
(req, res) => { res.send("OK"); });
My test file follows the sample here:
// index.spec.js
const {getFunction} = require('#google-cloud/functions-framework/testing');
require('../../');
describe("HelloTests", () => {
test("is testable", () => {
});
});
When I run jest I get the following error:
Cannot find module '#google-cloud/functions-framework/testing' from 'spec/unit/index.spec.js'
Some additional observations:
If I put that import statement into index.js and run the application, it imports just fine.
If I comment out the import statement from index.spec.js but leave it in index.js and run jest, I get the same error for the import in index.js.
This leads me to assume that Jest is not properly handling submodules. I've never worked with submodules like this before (that I can remember), so I'm at a complete loss. I did some digging and this is from the functions-framework node module's package.js:
"exports": {
".": {
"types": "./build/src/index.d.ts",
"default": "./build/src/index.js"
},
"./testing": {
"types": "./build/src/testing.d.ts",
"default": "./build/src/testing.js"
}
},
No idea if this is relevant but wanted to include it in case it's useful.
Any idea why I'm getting this error and/or how to resolve it without switching to ESM?
Update: I switched to ESM and get the exact same error.
This apparently got fixed earlier this year:
Issue: https://github.com/facebook/jest/issues/9771
Initial Release: https://github.com/facebook/jest/releases/tag/v28.0.0-alpha.3
I had copied an older (but still fairly recent!) package.json that was stuck on v27 so it wasn't picking up the latest library. Did a clean install and confirmed no further issue with at least v29.3.1.
Rookie mistake.

My Javascript file won't run because of bigint error

I am trying to use #metaplex/js to do some NFT minting. Usually my .js files work properly but when I run the file this error comes up.
bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)
I don't really get what that means. So, I tried to run npm run rebuild but rebuild is said to be a missing script and I couldn't find a way to install it.
Here is my code:
import { Connection, programs} from "#metaplex/js";
import { Loader } from "#solana/web3.js";
const { metadata: {Metadata}} = programs;
const connection = new Connection("devnet");
const tokenPublicKey = 'my_adress';
const run = async() => {
try{
const ownedMetadata = await Metadata.Loader(connection,tokenPublicKey)
console.log(ownedMetadata)
}
catch{
console.log('Failed to fetch')
}
};
run();
If you have any idea, or simply an explanation of what my error means, I'd be grateful.
You are getting this error because a nested dependency has a compilation step that might not succeed in your platform. This issue provides a good explanation.
[...] This happens because one of our dependencies (bigint-buffer) runs a compilation step on installation and this can step may fail for a couple of reasons. One of the reasons is that your system might not have the build-tools the library is looking for. You can install these build tools on Windows (see https://www.npmjs.com/package/windows-build-tools), but you don't actually need to as it automatically falls back to a pure JS solution instead. Though I agree... that warning is very annoying.
However, this should give you a warning and still allow you to compile your code.
It is worth noting that the current JS SDK from Metaplex is going to be deprecated in favour of the new one: https://github.com/metaplex-foundation/js-next
With the new JS SDK, you can fetch an NFT using the following piece of code.
import { Metaplex } from "#metaplex-foundation/js";
import { Connection, clusterApiUrl } from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const metaplex = new Metaplex(connection);
const mintAddress = new PublicKey("ATe3DymKZadrUoqAMn7HSpraxE4gB88uo1L9zLGmzJeL");
const nft = await metaplex.nfts().findByMint({ mintAddress });

Reason for node module #kenjiuno/msgreader error: MsgReader is not a constructor

I'm unable to get even the first lines of the example code from the relatively popular #kenjiuno/msgreader for parsing Outlook .msg files to work. I've installed the module with npm successfully, and my code is:
const fs = require('fs')
const MsgReader = require('#kenjiuno/msgreader')
const msgFileBuffer = fs.readFileSync('./test-email.msg')
const testMsg = new MsgReader(msgFileBuffer)
But I get the error: "MsgReader is not a constructor".
A quick console log of MsgReader returns { default: [Function: MsgReader] }. I also tried doing it as a function (no 'new' keyword) which also produced an error.
The only difference between my code and the example code is that they use import (import MsgReader from '#kenjiuno/msgreader') whereas I've used require, but presumably that couldn't make a difference?
Any ideas anyone?
I ended up changing the require statement to add ["default"] which fixed the issue:
const MsgReader = require('#kenjiuno/msgreader')["default"]
I looked at the library code and made a guess based on the export statement using that 'default' syntax. Is this issue something to do with commonJS or something? If anyone can explain this to me that would be great!

Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum

I'm enthusiastic about Deno so I'm giving it a try. Found a tutorial on building a REST API here.
So, when I'm trying to run it, I get this InvalidData error:
error: Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum
at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
at async Object.connect ($deno$/net.ts:216:11)
at async Connection.startup (https://deno.land/x/postgres/connection.ts:138:17)
at async Client.connect (https://deno.land/x/postgres/client.ts:14:5)
at async Database.connect (file:///Users/svenhaaf/git/deno/logrocket_deno_api/db/database.js:17:5)
Now, it looks to me that something is wrong when trying to connect to the database, but I can't really figure out what.
What does this InvalidData error mean? How should I fix this?
FYI my deno --version prints:
deno 0.42.0
v8 8.2.308
typescript 3.8.3
Code:
I cloned the repo from https://github.com/diogosouza/logrocket_deno_api, and in config.js, I edited line 1 from const env = Deno.env() to const env = Deno.env, since it looks like Deno.env became an object instead of a method.
The tutorial is not using versioned URLs, and deno-postgres version that is being used is not compatible with v0.42.0, since https://deno.land/x/postgres/mod.ts is pulling from master
Change db/database.js to import from https://deno.land/x/postgres#v0.3.11/mod.ts, since v0.3.11 is the correct version for Deno v0.42.0
import { Client } from "https://deno.land/x/postgres#v0.3.11/mod.ts";
Remember to always use the version in the URL if you don't want the code to stop working when a new Deno or package version is released.

Missing module exports in IE11/Edge

I'm having trouble getting an npm module to work since it was changed to ES2015.
I have an ES2015 app that is bundled by browserify and transformed with babelify. I am trying to upgrade an npm module named credit-card for credit card validation, which was changed from ES5 to ES6 in the current version. The problem starts with IE11/Edge. The code works fine on Chrome. Here's how the module is imported in the transformed app (babel'd code):
var _this = this;
var _creditCard = require('credit-card');
var _creditCard2 = _interopRequireDefault(_creditCard);
Here's a piece of code calling it:
this.validateCreditCard = function () {
var ccNumber = _this.account_number_credit_card.value.replace(/\D/, '');
_this.creditCardValidation = {
accountHolder: _this.account_holder_credit_card.value.replace(/\W/g, '').length >= 2,
cvc: _this.account_cvc_credit_card.value.replace(/\D/g, '').length > 2,
accountNumber: _creditCard2.default.isValidCardNumber(ccNumber, _creditCard2.default.determineCardType(ccNumber, { allowPartial: true }))
};
return _underscore2.default.all(_underscore2.default.values(_this.creditCardValida tion));
};
Now on Chrome this works without a problem. On IE however, the exported functions of the credit card module are missing.
Here's a printscreen of a console log of the module in IE
And here's Chrome
It looks like defaults is completely missing in IE. Is this a known issue? Do any of you have encountered this problem before and can give me some hints? Any pointers on how I could investigate this issue to understand what is going wrong and how I could fix it?
Stepping through the require() in IE11 Debugger i found out that there was a problem with Object.assign being undefined in IE11. After some searching I found this thread. The answer in this thread worked out in the end. I needed to add polyfill to my browserify bundle and enable the "transform-es2015-classes" plugin with the opt loose: true (See this thread for code).

Categories