baseUrl and paths in typescript - how - node.js

I've started an application in typescript. I've learned about some features of TS and it looked like something, that could help me, hovewer, I don't work like I would expect. The documentation of TS says something about Path mapping in Module resolution chapter. This module mapping can, if I understand it correctly, save me few or even lot of double-dots in import. So I have created a "inc" directory with one file (at this time), that will be included in multiple files in multiple directories. Into tsconfig I've written following:
"baseUrl": ".",
"paths": {
"#inc/*": [ "inc/*" ]
}
Now, I would expect, that using import { X } from "#inc/somefile" (even from file resting somewhere deep in folder tree) would result in importing that export X from ./inc/somefile.ts (or .js, when runnning).
Hovewer, the compiler/transpiler will leave the import statement intact, so when I try to run this code using node.js, it will die because there is no #inc/somefile - node doesn't read tsconfig and tsc doesn't create any mapping functions.
I can, of course, read and parse the path element by hand in some kind of require wrapper, but I believe there is something I'm doing wrong and/or better way to achieve this.
Thank you for your replies.

Remember that
if you then try to exeute the compiled files with node (or ts-node), it will only look in the node_modules folders all the way up to the root of the filesystem and thus will not find the modules specified by paths in tsconfig. -- introduced in tsconfig-paths readme.
In conclusion, directly require tsconfig-paths into dependencies list and load tsconfig file on run could be a quick solution.

Related

Package.json - set main directory

I'm building a library with no default export, but a whole set of sub-exports. It's documentation for a set of APIs, so each API is exported from its own sub-directory. There is no central API info that should be exported from, say, dist/index.js, but instead, there's dist/api-one/index.js, dist/api-two/index.js, etc.
Currently, I'm importing like so: import { SomeFeatureOfApiOne } from 'my-package/dist/api-one
But it'd be nice to be able to get rid of the dist in the import path, since everything will have it. I know the files parameter just determines which directories are included in the export, so that doesn't work, and it appears that main is for the actual module file, not a directory.
Is there a way to do this? I was thinking of maybe a postinstall script that moves the sub-directories from /dist to root, but that feels super hacky to me, so I was hoping there was a neater way.
Add:
"exports": {
"./*": "./dist/*.js"
},
to your package.json
You can read more about "exports" here - https://nodejs.org/api/packages.html#subpath-exports

VS Code: Debug TS code when stepping into a library function in the node.js debugger

I have written a library in TS and a program to test my library. I have enabled source Maps for both the library and the program and I am using the node.js debugger.
Debugging the TS code of my program works, but as soon as I step into a call of a library function, I am debugging the emitted JS code instead of my TS source.
I set the 'files' field of my library's package.json to [ "lib" ], where lib is the dir which contains the JS files as well as the source map, but that didn't change anything.
I there another way how to tell VS Code that it should use the source map of my library?
I finally found a solution. The problem is – of course – that the VS Code debug adapter can't find the source files of the lib. The key to resolve that issue is the "sourceRoot" option in the lib project's tsconfig.json.
Consider a lib project in dir myLib and another project in dir myProg that imports functions from myLib. The lib's source files are in myLib/src and the transpiled js files as well as the source maps are in myLib/dist. myLib and myProg reside in the same parent dir.
Now when I debug myProg, I want to be able to step into a call of a function imported from myLib and debug its TS source.
Regarding the paths to the source files stored in the lib's source maps, it is important to know that relative paths are resolved relative to the source map.
Let's take a look at the "sources" array in one of the lib's source maps:
"sources":["../src/main.ts"]
Since we are running myProg, this path gets myProg/src/main.ts, but that's not the path to the lib's main.ts.
Now, we add "sourceRoot": "../../myLib/src/" to the lib's tsconfig.json. We see that the relevant part of the source map has changed to
"sourceRoot":"../../myLib/src/","sources":["main.ts"]
Since this path is resolved relative to myProg/dist, it gets myLib/src/main.ts.
Now, we merely have to tell VS Code to look for source maps in myLib/dist too, which results in the following value for "outFiles" in myProg's launch.json:
"outFiles": [
"${workspaceFolder}/dist/*.js",
"${workspaceFolder}/../myLib/dist/*.js"
]
That's it. You may even set breakpoints in myLib's .ts files. They will be hit, but I observed that they were hit in the wrong order.
In that case, set a breakpoint in myProg somewhere before the first invocation of an import from myLib.
I didn't do extensive tests, but from what I observed, that seems to solve this issue.
If you experience the same like me, namely that you hit F5 and the program just runs without hitting any breakpoint, just hit F5 again and again until it works.
I tested with the #builtin #id:ms-vscode.js-debug as well with #id:ms-vscode.js-debug-nightly, each with "type": "node" and "type": "pwa-node", but that didn't change anything.
It seems to take less launches to work in case you open the entry point file and have a break point in it before launching, but I didn't test this extensively too, so it could just have happened by chance.

NodeJS import file with the same name as a folder

I have the following file structure: ([] are folders)
[MySQL]
ConnectionPool.ts
Connection.ts
MySQL.ts
In my code, I am using typescript to develop the app, which will be built to javascript for the production version. The development version is tested directly from the uncompiled typescript files, using babel with the following configurations:
{
"presets": [
["#babel/preset-env", {
"targets": {
"node": "current"
}
}],
"#babel/preset-typescript"
],
"plugins": [
"#babel/plugin-transform-runtime",
[
"module-resolver",
{
"alias": {
... list of some aliases
}
}
]
]
}
My problem is the following, I do most of my imports like this:
import ConnectionPool from 'MySQL/ConnectionPool`
which works for me, as when I run my dev code, the compiler correctly identifies the file extension to .ts, and it also correctly identifies the built versions file extension to .js.
But if I want to import my MySQL.ts file, I can't do it this way, as I will get the following error: Error: Cannot find module './'. If I specify in my import statement the file extension, everything works correctly, but then, when I build my code, there will be no more .ts files in there, so I will get errors there.
Strangely, on the frontend, where I use webpack, I get no complaints about importing files without extension whose name is the same as a folders name in the same directory. What solutions do I have for this issue, which does not revolve around renaming my files or folders in the structure?
Rename your file MySQL.ts to index.ts and move it into the folder MySQL
In the meantime, I resolved my problem by explicitly specifying .ts as the file extension, and when building the code, using the babel-plugin-transform-rename-import to replace the .ts extensions to .js extension.
I won't accept this as the correct answer, as this is too hacky for me, so if a better solution comes up, I am still open for it.
I don't believe what you want to do is possible, node will automatically include either the file or the directory but if both of them are called the same thing node will have no idea which one to import and it will always prefer one over the other.
Using import Example from 'example' will have node search either for any files called example.js or directories called example with an index.js and it will only load one of them.
The reason webpack does it correctly is because webpack will never bundle a "directory", it will take what you've specified as an import and try all of the resolves extensions until it finds one and then it will import that file, so you'll never have conflicting files with directories with webpack.
I thought maybe a solution is to use aliasing in your typescript config so that you can use import Example from '#example' and differentiate between your directories and files that way. Then you can also do import Example from 'example' if you just want to load the file itself. But even then I don't think that will even work because once it gets compiled to javascript you'll just have the same issue as before with conflicting paths.
That being said, while I understand being a little bit obsessed with naming conventions and small things, I really don't think you should be storing "mysql" outside of the "mysql" directory, for two reasons. The first reason is that it's part of that directory, that's what that directory is for, it contains the "mysql" stuff, so why would you want to store it outside. Secondly using a "index.ts" communicates something to other developers, when I open up a new project or directory I'm immediately looking for something called "index.ts" or similar, otherwise I have no idea where to even begin. Using "index.ts" is a good way to communicate to anyone that "this file right here is the one you're looking for, everything starts here". That being said, just call it index.ts and store it where it belongs.
You can try in your tsconfig.json to set moduleResolution to the classic strategy:
{
"compilerOptions": {
"moduleResolution": "classic"
}
}
Unfortunately, looking at the code, this seems to be impossible in your setup:
import is handled by module-resolver
module-resolver calls the NPM package resolve
resolve.sync checks for the no-extension case before testing extensions.
Given that most systems are going to follow Node module resolution, I think you're out of luck, without some manual aliases or moving files around.
FWIW, NodeJS says that extensions in import are mandatory.

babel-core 'transform' function cannot find plugin

I have a global node module that uses babel-core transform function.
I have no .babelrc at the root of my module.
It takes a file and basically just use transform to 'compile' it.
const result = transformSync(content, {
filename: src,
});
There is a .babelrc file along with the said file and I'm indeed able to find it
{
"presets": ["#babel/preset-env"]
}
but it complains about not finding '#babel/preset-env' which is right, because the module is installed with mine and not the file/.babelrc being transpiled.
I've tried many options in https://babeljs.io/docs/en/options but still can't make it work.
How can I configure transform so it get plugins from my module while loading babel configuration from the folder of the transpiled file ?
By design, Babel's plugin loader searches for plugins relative to the config file that references them, or uses the cwd for plugins passed directly in the transformSync options. Control of that isn't exposed to utilities calling Babel.
Changing those sematics would mean that a Babel config file would vary in behavior based on the tool that was loading it, which would be very inconsistent for users, especiall considering that one of the main benefits of having the config file format is so that config can easy be shared across multiple tools calling Babel, for instance one for tests and one for bundling.
If you want users to be able to customize your tool, it sounds like what you may actually want is your own entirely separate config file for your tool, so you can define whatever semantics you want for that.

Intellij IDEA resolve local require() path [ node.js ]

I'm trying to avoid relative require() calls in my express setup. I'd also like to avoid placing my code in the node_modules folder. In short, I'm trying to implement any of the methods described in this gist.
Any of those solutions will work fine for executing code with node or npm. However, I'm trying to find a solution that will also be supported by Intellij IDEA's code resolver, i.e. trying to make sure "go to declaration" and autocomplete hinting works.
I've tried the following
Setting NODE_PATH in the run configuration.
Using a global prefix, i.e. require( global.__base + "mylib").
Adding a symlinked folder to node_modules/.
Adding a symlink from a lib/ folder to node_modules/lib/ does work, but comes with two caveats:
Changes to the source files aren't picked up automatically, so I have to manually "synchronize" node_modules/lib, and
When "going to declaration", IntelliJ (of course) opens node_modules/lib/mylib instead of lib/mylib. This can lead to confusion as the actual file and the symlinked file can be open in separate windows.
Instead of a different way to require local paths (all these methods do work with node after all), I'd be happy with a way to hint to IDEA that it should search the lib/ folder for sources.
So, I realised that if you add a library through Project Structure > Libraries, it won't actually be enabled.
Instead, go to Preferences > Languages & Frameworks > Javascript > Libraries and add a new library. Set the framework type to node_modules, Visibility to Project and add your lib folder.
After adding it, make sure the Enabled checkbox is checked.
That's it, Intellij can now resolve your require('mylib') paths.
Use whatever method from the gist mentioned in the question to actually get node to resolve the paths.

Resources