Using TS absolute paths in import statement triggers an error in react-native - node.js

I am currently converting relative paths to absolute paths in my React-Native app and it triggers the following error:
Error response to absolute import
And I have set up my tsconfig.json as follows:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"#buttons/*": ["src/components/buttons/*"]
},
"jsx": "react",
"resolveJsonModule": true
}
}
The following statement is how it looks in the file that I am importing it in:
import {CoreButton} from '#buttons/CoreButton';
Any ideas or suggestions would be amazing :)

The solution to this problem has been found at the following link:
React native Typescript path alias unable to resolve module

Related

Mongoose + Typescript - Unable to require file: mongodb\index.ts

I have a Node + Express application with Typescript, which was running fine, until I decided to include Mongoose in the equation. When I try running it, I get the following error:
TypeError: Unable to require file: mongodb\index.ts
This is usually the result of a faulty configuration or import. Make sure there is a '.js', '.json' or other executable extension with loader attached before 'ts-node' available.
I'm running the application with Nodemon, and have the following configuration in nodemon.json:
{
"execMap": {
"ts": "ts-node"
}
}
Here's my tsconfig.json:
{
"compilerOptions": {
"esModuleInterop": true,
"moduleResolution":"node",
"baseUrl": ".",
"target": "es6",
"paths": {
"#controllers/*": ["./controllers/*"],
"#services/*": ["./services/*"],
"#routes/*": ["./routes/*"],
"#customTypes/*": ["./types/*"],
"#utils/*": ["./utils/*"],
"#graphql/*": ["./graphql/*"]
}
}
}
I'm kind of new to Node with Typescript, so I probably made some mistakes, but cannot find any info regarding what exactly is wrong.
Tried downgrading Mongoose, installing MongoDB manually and changed versions of #types/mongoose, but to no avail.

TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///path/to/data.json" needs an import assertion of type "json"

I'm trying to import JSON in nodejs.
// tsconfig.json
...
"lib": ["es2022"],
"target": "es2022",
"module": "nodenext",
"moduleResolution": "node",
...
"resolveJsonModule": true,
...
// .swcrc.json
...
"target": "es2022",
...
"module": {
"type": "nodenext",
...
When I then compile it and run "start": "NODE_ENV=production node --es-module-specifier-resolution=node --experimental-json-modules --no-warnings lib/index.js" I get TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module "file:///path/to/data.json" needs an import assertion of type "json".
I then add:
import data from './data.json' assert {type: 'json'}
console.log(data)
I then open up the compiled code and I can see:
import data from"./data.json";console.log(data);
//# sourceMappingURL=index.js.map
At this point I thought maybe it's SWC not compiling the assertation?
I then run tsc --emitDeclarationsOnly and I get Import assertions are not allowed on statements that transpile to commonjs 'require' calls. At this point I have no idea why on earth commonjs has anything to do with it, I'm not using commonjs anywhere am I?
Also I'm using node 18.
What am I doing wrong? I am simply trying to import that json.
Edit: Okay so the reason TS was breaking was because of missing "include": ["src/**/*.ts", "src/**/*.json", "types.d.ts"],. After adding that it now works. Unfortunately SWC is still giving the same error so I cannot run it.
Finally figured it out. There's an experimental option in .swcrc.json that allows you to tell it to keep the assertations.
// .swcrc.json
...
"jsc": {
"experimental": {
"keepImportAssertions": true
}
}

"Could not dynamically require 'binding.node'" when trying to rollup speaker module

I'm trying to use rollup to bundle the speaker module.
Once it builds and I try to run it, I get the following error:
Error: Could not dynamically require "/path/to/Project/build/binding.node". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of #rollup/plugin-commonjs appropriately for this require call to work.
From the build:
const os = require$$0__default$3["default"];
const debug = src.exports('speaker');
const binding = bindings.exports('binding'); // Error occurs here
I've tried to add the path and version of it to dynamicRequireTargets with no luck. Thing is, there is no Project/build folder, so I'm not sure if it only exists during build time or if it's a fake path.
How can I get this to build and run correctly?
Minimal reproducible example
$ npm init
$ npm i --save speaker
src/index.ts
import * as Speaker from 'speaker';
console.log(Speaker);
rollup.config.ts
import * as fs from 'fs';
import path from 'path';
import executable from 'rollup-plugin-executable';
import commonjs from '#rollup/plugin-commonjs';
import json from '#rollup/plugin-json';
import { nodeResolve } from '#rollup/plugin-node-resolve';
import typescript from '#rollup/plugin-typescript';
const incrementalDependencyLoader = {
input: 'src/index.ts',
output: {
file:
'/dist/' +
require(path.join(process.cwd(), 'package.json')).name,
// cjs translates to CommonJs which is supported by Node
format: 'cjs',
banner: '#!/usr/bin/env node\n',
},
plugins: [
nodeResolve(),
typescript({
tsconfig: fs.existsSync(path.join(process.cwd(), './tsconfig.build.json'))
? './tsconfig.build.json'
: './tsconfig.json',
}),
json(),
commonjs({}),
executable(),
],
external: [],
};
// with using an array, we can create multiple bundled javascript files
export default [incrementalDependencyLoader];
tsconfig.json
{
"compilerOptions": {
"jsx": "preserve",
"module": "esnext",
"moduleResolution": "node",
"target": "esnext",
"lib": ["esnext"],
"baseUrl": ".",
"allowSyntheticDefaultImports": true
}
}

Exporting Global Styles with Font Assets from a TypeScript->CommonJS module

I have a TypeScript React project organized as follows:
tsconfig.json
package.json
yarn.lock
lerna.json
node_modules/
packages/
ui-library/
package.json
tsconfig.json
typings.d.ts
src/
fonts/
myfont.ttf
components/
GlobalStyle.tsx
lib/ <-- `tsc` builds to here
web-app/
package.json
src/
components/
The web-app imports the ui-library as a commonjs module in its package.json. This is managed through Yarn Workspaces, hence node_modules being at the root instead of each folder. At one point, the web-app imports GlobalStyle from the ui-lib, which is where the issue occurs.
Error: Cannot find module '../fonts/myfont.ttf'
Require stack:
- /Users/me/sources/myproject/packages/ui-library/lib/styles/GlobalStyle.js...
Here is the original import statement from ui-library/src/GlobalStyle.tsx that causes the issue:
import myFont from "../fonts/myfont.ttf";
const GlobalStyle = () => (
<style global jsx>{`
#font-face {
font-family: "My font family";
src: url(${myFont}) format("truetype");
}
...</style>);
The issue is the require statement in the emitted GlobalStyle.js code, built when I run tsc in the ui-lib folder:
const MYFONT_ttf_1 = __importDefault(require("./myfont.ttf"));
I googled this issue online, and I found you had to add typings for compiling .ttf and other abnormal imports. So I created a typings.d.ts file with this declaration:
declare module "*.ttf" {
const value: string;
export default value;
}
And I included it on ui-library/tsconfig.json as follows:
{
"extends": "../../tsconfig.json",
"exclude": ["lib"],
"include": ["src"],
"files": ["./typings.d.ts"],
"compilerOptions": {
"baseUrl": "src",
"outDir": "lib",
"declaration": true,
"declarationMap": true,
"noEmit": false
}
}
The tsconfig above extends the root tsconfig:
{
"files": ["./typings.d.ts"],
"compilerOptions": {
"module": "commonjs",
"target": "es2019",
"lib": ["dom", "es2019"],
"strict": true,
"jsx": "react",
"moduleResolution": "node",
"isolatedModules": true,
"esModuleInterop": true,
"noUnusedLocals": false,
"forceConsistentCasingInFileNames": true,
"strictNullChecks": true,
"sourceMap": true,
"noEmit": true,
"declaration": false
},
"exclude": ["node_modules"]
}
We are using TypeScript 3.8. Let me know if there is any additional info to provide. My hunch is that I am either using the wrong module/target, or fundamentally misunderstanding some aspect of this.
More Details
I should note the reason we are using CommonJS modules is because ts-node can only work with that. We pull in ts-node when we are doing our gatsby build, following the gist here in gatsby-config.js:
require("ts-node").register();
// Use a TypeScript version of gatsby-config.js.
module.exports = require("./gatsby-config.ts");
Maybe it's an impossible problem to solve, to get fonts imported through ts-node which is a server side environment? Confused on what the right approach is to export a module with fonts. Willing to get rid of ts-node, and leave the Gatsby config files as js.. but mostly just want to be able to import my fonts.
I solved this by just copying the fonts as part of build steps. Basically, fonts have their own pipeline. There may be better ways, but this works well enough.

importing class in Node js with typescript

I would import class in nodejs and use it in app.ts
var nano = require("nano");
import { EnvConfig } from './envConfig.service';
let config = new EnvConfig();
const dbCredentials: any = config.appEnv.getServiceCreds('dataservices');
export const nanodb = nano({
url: dbCredentials.url,
});
export const nanodbCockpitLight = nanodb.use('data');
console.log(dbCredentials);
When I try to compile I get this error.
import { EnvConfig } from './envConfig.service';
^
SyntaxError: Unexpected token {
I have created the tsconfig file :
{
"compilerOptions": {
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"allowSyntheticDefaultImports": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"allowJs": true,
"outDir": "./dist",
//"baseUrl": "src" // Attention !! nécessite l'utilisation d'un loader de module node pour fonctionner sur node
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
I get this warning
No inputs were found in config file 'c:/Users/EHHD05911.COMMUN/Documents/cockpitLight/DB mananger/tsconfig.json'. Specified 'include' paths were '["src//"]' and 'exclude' paths were '["node_modules","/.spec.ts"]'
You cannot run node app.ts file directly that won't work
You need transpiler like babel js or typescript compiler tsc so first transpile to js file and then run node app.js
You're using .js extension, you need .ts extension, e.g.: app.ts instead of app.js.
Make sure you have typescript either in npm global or in dev dependencies.
I suspect whatever you're importing has typescript syntax (strong typing and such), and so running node directly won't work. You need to run tsc first, which will transpile everything to javascript in a dist folder, and then run node dist/app.js.
This is a bit cumbersome though, which is why there is ts-node. It's exactly what it sounds like, a node REPL for typescript. You should be able to run ts-node src/app.ts.
import { something } is a typescript syntax, it won't work in a .js file. That is a separate language. Try using require instead.
Use babel js which is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
package.json
"dependencies": {
"#babel/polyfill": "^7.0.0",
}
"babel": {
"presets": [
"#babel/preset-env"
]
},
"scripts": {
"start": "server.js --exec babel-node",
}
https://babeljs.io/docs
This will enable/resolve your import statements.

Resources