Importing all json files from a directory not working - javascript

I have a vanilla js project that I am building with parcel. In project I have a directory with a lot of json files that I would like to use in one of my modules. I have tried to import them like I would import js files but that didn't work.
import * as regions from './Polygons'
How could I import all the files and iterate over them like you would iterate over an array of objects?

import only works if the thing you are importing is an ES6 module. Just use require in a try-catch:
import fs
dir = './Polygons'
allFiles = fs.readdirSync(dir).map (filename) ->
try
json = require(dir + '/' + filename)
catch e
error = e
return { filename, json, error }

Related

How can I import & export modules in Node.js where I have the module names and directories as strings?

My folder structure looks like this:
modules
module-and
index.js
module-not
index.js
module-or
index.js
module-xor
index.js
moduleBundler.js
The file I'm working in, moduleBundler.js, imports the modules from each module folder / file, then exports them all as one bundle:
import ModuleAnd from "./module-and";
import ModuleNot from "./module-not";
import ModuleOr from "./module-or";
import ModuleXor from "./module-xor";
export { ModuleAnd, ModuleNot, ModuleOr, ModuleXor };
How can I make this code automatically import and export each of these modules, without needing to hardcode their names and directories within moduleBundler.js?
I'm able to get the names and directories of each of the modules with this code:
const moduleDirectories = getDirectories(__dirname);
const moduleNames = moduleDirectories.map(x => x.slice(0, 1).toUpperCase() + camelise(x).slice(1));
console.log(moduleDirectories);
>>> [ 'module-and', 'module-not', 'module-or', 'module-xor' ]
console.log(moduleNames);
>>> [ 'ModuleAnd', 'ModuleNot', 'ModuleOr', 'ModuleXor' ]
But there doesn't seem to be an obvious way of importing or exporting modules using these values.
I tried looping over each folder and importing them like this:
for (const i in moduleNames) {
import moduleNames[i] from ("./" + moduleDirectories[i]);
}
>>> ReferenceError: from is not defined
I also tried using eval(), knowing its security risks, just to see if it would work:
for (const [key, value] of Object.entries(moduleNames)) {
const directory = "./" + moduleDirectories[parseInt(key)];
eval(`import ${value} from "${directory}"`);
}
>>> SyntaxError: Cannot use import statement outside a module
I know for eval() I could maybe get it working by adding "type": "module" to my package.json, but I'd rather avoid doing that if possible. I'd rather avoid eval() entirely, too, if possible.
Also, once I have got them imported, how can I then export them as a bundle?
Solved it! Turns out I needed to use require instead of import, d'oh!
Using the arrays moduleDirectories and moduleNames which I created earlier:
for (const i in moduleDirectories) {
const directory = "./" + moduleDirectories[i];
module.exports[moduleNames[i]] = require(directory).default;
}

How to import a JSON5 file (as one can regular JSON) in Typescript?

I would like to import a JSON5 file into a Javascript object in the same way [one can import a JSON file](import config from '../config.json').
Shows this message on hovering but it's clearly there
Cannot find module '../conf/config.json5' or its corresponding type declarations.ts(2307)
I have 2 side questions related to the main one above:
Will I get intelisense for contents inside .json5, like regular json
Does it even work like it works with require()? Do I have to use import() instead of regular import ?
You will need the package to do so: json5.
There are one of two ways we can use this:
One: (target module system is CommonJS) require it
Following the README, we register json5:
import "json5/lib/register";
Then you can use require to import it:
const config = require("../config/config.json5");
Two: Reading the file and then using json5 to parse it:
import json5 from "json5";
import { readFile } from "fs/promises";
(async () => {
const text = await fs.readFile("./path/to/config.json5"); // path to config.json5 from entry point
const config = json5.parse(text);
})();
You can also use the provided CLI to convert json5 files to regular json that you can use.
The creator updated the json5 wiki
Wiki
You need to create an extra file with .d.ts extension to support intellisense.

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)
}
:)

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');

Import nodejs module with version number into typescript

So I have a node module which seems to use a versioning system. Using nodejs I simply used
const Package = require('package-name').V1;
which worked without issues. Typescript however does not like the .V1 so I use
import { Package } from 'package-name';
which complies fine but the typescript output to javascript is
const package_name_1 = require("package-name");
Which means that any function or properties of package_name_1 are undefined since the module doesn't seem to load V1.js file (i assume that is how it works..)
So I tried
import * as Package from 'package-name';
But it outputs the same javascript as before..
The actual folder structure of the package I am using is
-node_modules
--package-name
---client
----v1
----v1.js
with the v1.js file looking like
var PackageV1 = {}
PackageV1.CONSTANTS = require('./v1/constants');
PackageV1.Request = require('./v1/request');
PackageV1.Session = require('./v1/session');
...
module.exports = PackageV1;
Of course things like
const Package = require('package-name.V1');
do not work
Error: Cannot find module 'package-name.V1'
How can I require this V1.js file / directory using the typescript method?
As was hinted at in the comments
import * as Package from 'package-name';
is fine but when using the package I had to use
Package.V1.Request()
rather than
Package.Request()

Categories