Importing constans from one JavaScript file to another one - javascript

I'm trying to import the constans from one JS file to another JS file.
Consider the following files:
Constans file (consts.js):
const cars = ["honda","mitsubishi","mercedes"];
export { cars };
Main javascript file (main.js):
import { cars } from './consts.js';
let initNumberOfCars = 0;
let speed = 80;
...
But I get the following error on line 1 at main.js:
Uncaught SyntaxError: Unexpected token {
How should I import the consts from one js file to another one?

Your code should work as is. It must be a Babel issue. If you don't have babel you'll need to look into setting it up with Webpack or Parcel for minimal config.
https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
https://parceljs.org/
https://webpack.js.org/
https://babeljs.io/

Related

how to correctly use Google Protobuf, when using imports in Javascript

Lets suppose there are two .proto files, file hello.proto and file core.proto.
File core.proto is imported with import statement like
import "core.proto";
content of files:
hello.proto
syntax = "proto3";
import "core.proto";
message GetBalance {
string address = 1;
}
core.proto
syntax = "proto3";
message Block {
string chain = 1;
}
I run protoc with
protoc --proto_path=./ --js_out=import_style=commonjs,binary:./ *.proto
Javascript files are generated, but because of "import" statement there is something like
goog.object.extend(proto, core_pb);
and thats a problem because when I try to import this javascript file into my code,
import * as hello_pb from './hello_pb'
it does not work, it says "proto is not defined" it is a reference error.
What am I doing wrong?
Thanks!
While this answer will not directly solve your import problem, it may give you a workaround.
An alternative to "compiling" protobuf into JS is to use protobufjs which implements protobuf and can handle loading arbitrary .proto files. It has its disadvantages (not as lightweight as your solution could be) but it works well.
Assuming you distribute your .proto in your environment (service, app, whatever it is) importing protobufjs and deserializing a message would be something like:
import { loadSync } from 'protobufjs';
...
const protoRoot = loadSync('path/to/hello.proto'));
const Hello = protoRoot.lookupType('Hello'); // can be some_namespace.Hello
...
let message = Hello.decode(buffer);
Most (if not all) datatypes and encoding/decoding is supported. Check out protobuf project page.

module.export in typescript. import json list

It seems simple, this operates in javascript, but I'm a bit confused about typescript's closest equivalent. I'm trying to use module.exports in the way I know from javascript, passing data the json list data between 3 files.
in javascript the main file basically works as this: -
main.js :
const { mainnet: addresses } = require("./addresses");
const token0 = addresses.tokens.busd;
so, main.ts would be? (i believe main issue is here):
import { mainnet } from "./addresses/index";
token0 = mainnet.tokens.busd;
then typescript index.ts in ./address/index.ts (i believe this functions properly):
import tokensMainnet from './tokens-mainnet.json';
declare var module: any;
// "allowSyntheticDefaultImports" = true
module.exports = {
mainnet: {
tokens: tokensMainnet
}
};
and tokensmainnet.json
{
"busd": "0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56",
"wbnb": "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
}
i can see from the metadata it's functioning:
so I believe the main problem with with importing this module in the main.ts
I've grazed over some sources such as with no luck https://www.typescriptlang.org/docs/handbook/modules.html
in typescript
add
"resolveJsonModule":true
to package.json:
" Allows importing modules with a ‘.json’ extension, which is a common practice in node projects. This includes generating a type for the import based on the static JSON shape." -https://www.typescriptlang.org/tsconfig#resolveJsonModule
so add to main.ts:
import * as data from "./addresses/tokens-mainnet.json"
//...program code...
constructor(){
let tokenAddress = data
console.log(tokenAddress.busd)
}
:)

How to use functions from different part of my code in jest testing?

I'm trying to write a test in jest.
I have 2 functions in a different js file that i need to use in order to pass
data to the function im testing.
i tried to use:
import {func} from './funcfile' gives:
SyntaxError: Cannot use import statement outside a module
const {func} = require('./funcfile') gives:
SyntaxError: Unexpected token 'export'
looking at other topics and google, tried every dependency installation and added configurations to package.json, jest.config.js, .babelrc, babel.config.js.
the only thing that happened is getting an error around type ErrorHandler = ...
where it says a syntax error again excepted ";"
i reverted everything therefore i don't have the files with the changes, willing to try any solution you may seem fit.
it crashes on export const phone_number and never event get to the getSubCategory export line....
Edit:
Been asked to add some more code so others could understand better,
Thing is there is not much more code.
I have a file with lots of export const = ;
(as described in photo)
and eventually the function export const (as described in photo)
on my jest file i just have the import/ require line I added and the test fails there.
the error i get when using the suggested answer :
You can import your utils class and use constants as properties of this exported module, e.g.
import * as UTILS from './utils';
...
UTILS.getSubCategoryId('return input')
where utils is
export const getSubCategoryId = (category) => category;
Please check example
https://stackblitz.com/edit/typescript-rujqvm?file=index.ts
Combined with VadimB solution had to add these lines to .babelrc on root directory
{
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Now its all up and working

Is there a way to import .html file from JavaScript?

I have the following import statements in my Cloudflare Worker project, to import a html file as a string constant :
import userAgentJsch from './userAgentJsch';
import { parse } from 'cookie';
import test from '.test.html';
It fails with the error:
Module not found: Error: Can't resolve '.test.html' in
I was reading about needing to configure my webpack.config.js file, but I don't have such a file.
Can you please help? I just want to keep my html file separated from the js files, but I can't find a solution I can understand.
View folder structure is used for rendering templates no doubts
to read files in nodejs use this :
const fs = require("fs");
const files = fs.readFileSync("new.html");
and to import
var htmlContent = require('path/to/html/file.html');

How do I call a function in an external js file using typescrpt

We are trying a POC of adding Typescript and Webpack to our Angularjs project.
I am able to get my webpack bundle to generate, however at runtime the program cannot find the various functions in my validator.js. Can you please offer some advice?
login-view.components.ts
declare var findFormNode: any; //function in validator.js
//LogInUser
self.login = function ($event, command) {
if (findFormNode($event.target.id)) {
...
}
}
main.ts is importing the file
import "./../../../CommonStaticFiles/include/js/Validators.js";
bundle.js
eval("/* WEBPACK VAR INJECTION */(function($) {/*\r\n\r\n VALIDATORS\r\n\r\n ... n\n\nfunction findFormNode(
error
ReferenceError: findFormNode is not defined
at LoginController.self.login (login-view.component.ts:28)
at fn (eval at compile (angular.js:NaN), <anonymous>:4:267)
at callback (angular.js:29019)
In order for your functions to be properly imported, there are few things that you have to make sure of.
First, make sure you are exporting your functions correctly. Here's an example of how to export a function from Validator.js:
export const validateFunc1 = ():void => {};
Next, you have to make sure you are using proper import syntax. In order to import the function above, you would do the following:
import {validateFunc1} from "./../../../CommonStaticFiles/include/js/Validators.js";
Alternatively, if you want to import all exported functions at once, then you can use this syntax:
import * as validatorFuncs from "./../../../CommonStaticFiles/include/js/Validators.js";
Lastly, check that the location of Validators.js is correct. It's a common mistake to be looking in the wrong directory. Your code editor can usually help you find the right path to use.

Categories