How to import an Interface from a dependency of a dependency - node.js

Simple question, we have a custom package that uses axios as a dependency and exports a function that returns an Axios Client with some custom default configuration. The problem is that I want the AxiosInstance interface that is not exported from the package itself and axios it's not a dependency in my project.
// #myCustomDep
import { AxiosInstance } from 'axios';
export function createAxiosClient(): AxiosInstance { //... }
// Main project
import { createAxiosClient } from '#myCustomDep';
// Err: Cannot find name 'AxiosInstance'.
function buildClient(): AxiosInstance {
const axiosClient = createAxiosClient();
return axiosClient;
}
What would be the correct way of handling this import without modifying the underlying dependency (if possible)?

As long as it is a dependency of your dependency, you may very well also list it as your own dependency.
But even without doing so, you can still directly import from a transitive dependency.
TypeScript will only complain if it cannot find it in your node_modules, whether you have listed it as a dependency or not.
You can also use TypeScript utility types: ReturnType<typeof createAxiosClient>
https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype
Obviously, if possible, you would have your custom dependency re-export whatever is exposed by its API.

Related

(webpack) How to import webpack bundled modules as one instance in all require

I am implementing server-side rendering using react and express. So, I am using the context of react in Express.
However, the problem is that every time the context below is requeried, a new context is created and the context cannot be shared by other modules.
import { createContext, ReactElement } from "react";
type State = {
main: ReactElement | null;
srcList: Array<string> | null;
};
export default class Context {
static HtmlContext = createContext<State>({
main: null,
srcList: [],
});
}
What I wanna know is how to import webpack bundled modules as one instance in all require.
Similar to the singleton pattern, I was trying to find a webpack configuration that allows only one instance to be shared. And I was trying to use optimization option with runtimeChunk: 'single'. But it didn't work well and I don't know if I understood it well...
I would be very grateful if you could learn how to approach it.

Create a TypeScript library with optional dependencies resolved by application

I've written a library published to a private npm repo which is used by my applications.
This library contains utilities and has dependencies to other libraries, as an example let's choose #aws-sdk/client-lambda.
Some of my applications use only some of the utilities and don't need the dependencies to the external libraries, while some applications use all of the utilities.
To avoid having all applications getting a lot of indirect dependencies they don't need, I tried declaring the dependencies as peerDependencies and having the applications resolve the ones they need. It works well to publish the package, and to use it from applications who declare all of the peerDependencies as their own local dependencies, but applications failing to declare one of the dependencies get build errors when the included .d.ts files of the library are imported in application code:
error TS2307: Cannot find module '#aws-sdk/client-kms' or its corresponding type declarations.
Is it possible to resolve this situation so that my library can contain many different utils but the applications may "cherry-pick" the dependencies they need to fulfill the requirements of those utilities in runtime?
Do I have to use dynamic imports to do this or is there another way?
I tried using #ts-ignore in the library code, and it was propagated to the d.ts file imported by the applications, but it did not help.
Setup:
my-library
package.json:
peerDependencies: {
"#aws-sdk/client-lambda": "^3.27.0"
}
foo.ts:
import {Lambda} from '#aws-sdk/client-lambda';
export function foo(lambda: Lambda): void {
...
}
bar.ts:
export function bar(): void {
...
}
index.ts:
export * from './foo';
export * from './bar';
my-application1 - works fine
package.json:
dependencies: {
"my-library": "1.0.0",
"#aws-sdk/client-lambda": "^3.27.0"
}
test.ts:
import {foo} from 'my-library';
foo();
my-application2 - does not compile
package.json:
dependencies: {
"my-library": ...
}
test:ts:
import {bar} from 'my-library';
bar();
I found two ways of dealing with this:
1. Only use dynamic imports for the optional dependencies
If you make sure that types exported by the root file of the package only include types and interfaces and not classes etc, the transpiled JS will not contain any require statement to the optional library. Then use dynamic imports to import the optional library from a function so that they are required only when the client explicitly uses those parts of the library.
In the case of #aws-sdk/client-lambda, which was one of my optional dependencies, I wanted to expose function that could take an instance of a Lambda object or create one itself:
import {Lambda} from '#aws-sdk/client-lambda';
export function foo(options: {lambda?: Lambda}) {
if (!lambda) {
lambda = new Lambda({ ... });
}
...
}
Since Lambda is a class, it will be part of the transpiled JS as a require statement, so this does not work as an optional dependency. So I had to 1) make that import dynamic and 2) define an interface to be used in place of Lambda in my function's arguments to get rid of the require statement on the package's root path. Unfortunately in this particular case, the AWS SDK does not offer any type or interface which the class implements, so I had to come up with a minimal type such as
export interface AwsClient {
config: {
apiVersion: string;
}
}
... but of course, lacking a type ot represent the Lambda class, you might even resort to any.
Then comes the dynamic import part:
export async function foo(options: {lambda?: AwsClient}) {
if (!lambda) {
const {Lambda} = await import('#aws-sdk/client-lambda');
lambda = new Lambda({ ... });
}
...
}
With this code, there is no longer any require('#aws-sdk/client-lambda') on the root path of the package, only within the foo function. Only clients calling the foo function will have to have the dependency in their
node_modules.
As you can see, a side-effect of this is that every function using the optional library must be async since dynamic imports return promises. In my case this worked out, but it may complicate things. In one case I had a non-async function (such as a class constructor) needing an optional library, so I had no choice but to cache the promised import and resolve it later when used from an async member function, or do a lazy import when needed. This has the potential of cluttering code badly ...
So, to summarize:
Make sure any code that imports code from the optional library is put inside functions that the client wanting to use that functionality calls
It's OK to have imports of types from the optional library in the root of your package as it's stripped out when transpiled
If needed, defined substitute types to act as place-holders for any class arguments (as classes are both types and code!)
Transpile and investigate the resulting JS to see if you have any require statement for the optional library in the root, if so, you've missed something.
Note that if using webpack etc, using dynamic imports can be tricky as well. If the import paths are constants, it usually works, but building the path dynamically (await import('#aws-sdk/' + clientName)) will usually not unless you give webpack hints. This had me puzzled for a while since I wrote a wrapper in front of my optional AWS dependencies, which ended up not working at all for this reason.
2. Put the files using the optional dependencies in .ts files not exported by the root file of the package (i.e., index.ts).
This means that clients wanting to use the optional functionality must
import those files by sub-path, such as:
import {OptionalStuff} from 'my-library/dist/optional;
... which is obviously less than ideal.
in my case, the typescript IDE in vscode fails to import the optional type, so im using the relative import path
// fix: Cannot find module 'windows-process-tree' or its corresponding type declarations
//import type * as WindowsProcessTree from 'windows-process-tree';
import type * as WindowsProcessTree from '../../../../../node_modules/#types/windows-process-tree';
// global variable
let windowsProcessTree: typeof WindowsProcessTree;
if (true) { // some condition
windowsProcessTree = await import('windows-process-tree');
windowsProcessTree.getProcessTree(rootProcessId, tree => {
// ...
});
}
package.json
{
"devDependencies": {
"#types/windows-process-tree": "^0.2.0",
},
"optionalDependencies": {
"windows-process-tree": "^0.3.4"
}
}
based on vscode/src/vs/platform/terminal/node/windowsShellHelper.ts

How to use global variables in nest.js?

Taking configuration as an example, the Nest.js documentation advocates registering Config Modules and injecting them into other modules in a dependency injection way.
The benefits are obvious, and the dependencies and code are clear, but what if I have a nest.js project that needs to invoke the configuration information at startup? This actually caused me trouble.
My idea is to use a store (actually a closure) to manage all the variables that might be needed globally, the client-side link objects, registered at startup, and introduced when needed.
When corresponding variables are registered in this way, they can be introduced anywhere. The drawback is that you need to manage dependencies yourself.
With the above concept design of demo: https://github.com/sophons-space/nest-server.
Please e help me correct, I am still a rookie.
If you want to use Nest flow it should be defined in the configuration file
// app.module.ts
import configuration from './config/configuration';
imports: [
// first import as first initialization
ConfigModule.forRoot({
isGlobal: true, // to get access to it in every component
load: [configuration],
}),
]
...
// configuration.ts
export default (): any => {
return {
someGlobalConfigVariable: parseInt(process.env.PORT, 10) || 3000,
};
};
Create a file global.service.ts (inside a folder you can name it utils or whatever) & put the code bellow
export class GlobalService{
static globalVar: any;
}
Set value to the globalVar
GlobalService.globalVar = 'some value';
Get value from globalVar
console.log(GlobalService.globalVar);
N.B. Don't forget to import GlobalService wherever you want to use.
The way you can approach this is similar to how NestJS libraries or integrations usually handle configuration; using a method on the base module.
main.ts
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
// Note the `configure`-method
const app = await NestFactory.create(AppModule.configure({
myConfig: 'value',
});
await app.listen(3000);
}
bootstrap();
app.module.ts
import { DynamicModule } from '#nestjs/common';
export class AppModule {
static configure(config): DynamicModule {
return {
module: AppModule,
providers: [{ provide: 'CONFIG', useValue: config }],
// ....
}
}
}
You can use the general NodeJS approach
global.SomeGlobalVariableName = 'SomeGlobalVariableValue';
console.log(SomeGlobalVariableName);
Approach I used is using my config variables in yaml files and then getting those variables or objects wherever I want in my Nestjs project using config package. e.g in default.yml file
key: value
and then in file where I want to use this
import config from 'config';
let value = config.get<string>('key');
you can take this pkg from this npmjs link here
Why not go with more NestJs way i.e. with provide instance scope?
Most of the answers posted here are correct and easy to implement but I have a more generic way to define that variable that fits well in NestJs (Nestjs Scope and Dependency Injection flow). I would be happy to share the sample code, if required
Steps
Create a provider
Add a private instance variable to this provider - instead of a class variable (i.e. static variables) use an instance variable as NestJs automatically (by default) manages the instance of its providers in a singleton way i.e. a single instance of the provider is shared across the entire application. Read more about scopes here
Add get/set and other methods for that variable
Inject that provider wherever you need the global variable (instance variable of the provider(per instance).
Other ways of doing it
Config - preferrable for pre-defined types(like string, number...)
Static variable in util.ts file
Native Global variable - I would not recommend this(explanation is outside the scope of the question)

How to avoid singleton in node

I have an npm dependency that I import into a file of my server node. I wish it was not a singleton because it should not be shared between each request.
The file who import the dependency :
const dependency = require('dependency');
export class dependencyFactory {
public static getDependency() {
return dependency;
}
}
index.js of dependency in node_modules :
const path = require('path');
const createApi = require('./createApi');
module.exports = createApi(path.join(__dirname, './lib/providers'));
How can i do that ? thank you.
Modules result in singletons in Node. If this is undesirable, a workaround always depends on specific package.
A preferable way is to export factory function or constructor class from a package that can create new instances when needed.
If this is not possible, possible workarounds may include:
use package internal modules to create new instances
invalidate module cache to re-import a package
get class constructor from a singleton and create a new instance
All of them can be considered hacks and should be avoided when possible. E.g. relying on internal package structure may introduce breaking changes with new package version, even if package changelog doesn't assume breaking changes. And a pitfall for cache invalidation is that a package may consist of numerous modules that should or should not be re-imported.
The first workaround seems to be applicable here.
const createApi = require('dependency/createApi');
const instance = createApi(require.resolve('dependency/lib/providers'));
A cleaner solution is to fork a package and add a capability to create multiple instances.

Typescript : Add a method on a class from another module / Populate a namespace from different modules

The story
I am building a modular library for math operations. I also want to divide the library into multiple modules : core, relational, vectors, and so on. The modules can be used on their own (but all depend on the core module)
I know it's not possible to use partial classes How do I split a TypeScript class into multiple files? / https://github.com/Microsoft/TypeScript/issues/563
The problem :
The core module defines the Set class, which is a mathematical set. It defines operations such as Set#add, Set#remove.
Though, the optional relational module adds a Set#productoperator on the Setclass.
Other modules could also add other operations on the Set class. I want to keep the possibility of adding functionality when I will see fit.
The question
With typescript, how can I add a method on a class that resides in another module ?
How can I arrange the typings so that the user of my library will see the Set#product in his code completion only if he installed the relational module ? Otherwise he only sees the #add and #remove operations ?
I am developing this library for node.js, but also use browserify to bundle it for browser use.
// core/set.ts
export class Set {
add(element){}
remove(element){}
}
// relational/set.ts
import {Set} from './../core/set.ts';
Set.prototype.product = function(){} // ?
// app/index.js
import {core} from 'mylib';
var set = new Set();
set.add();
set.remove();
// set.product() is not available
// app/index2.js
import {core} from 'mylib';
import {relational} from 'mylib';
var set = new Set();
set.add();
set.remove();
set.product() //is available
Bonus question
All these modules are made to be available through a common namespace, let's call it MyLibrary. The core module adds MyLibrary.Core, and the relational module adds some objects into the MyLibrary.Core, and also adds MyLibrary.Relational.
Let's say I publish another module, only used to act as a facade for the other modules. Let's call this module my-library.
If a user installs the my-library, core and relational modules with npm.
npm install my-library && npm install core and nom-install relational
In the client application I would like the user of the library to only have to write
var lib = require('my-library');
Then, my-library would automatically check all installed MyLibrary modules, require them and populate the MyLibrary namespace and return it.
How an I tell the my-library module, the first time it is accessed, in both node and browser env to
Check for any available MyLibrary module (browser and node environments)
Run a method for each module (to install them in the namespace)
Return that nice fruity namespace
If you're just writing declaration files, you can use interfaces instead and do something like what moment-timezone does.
moment.d.ts
declare module moment {
interface Moment {
// ...
}
interface MomentStatic {
// ...
}
}
declare module 'moment' {
var _tmp: moment.MomentStatic;
export = _tmp;
}
moment-timezone.d.ts
Just redeclare the same interfaces with extra functions.
declare module moment {
interface Moment {
tz(): void;
}
interface MomentStatic {
tz(): void;
}
}
declare module 'moment-timezone' {
var _tmp: moment.MomentStatic;
export = _tmp;
}
Both packages are identical now, and moment gets the new methods automatically.

Resources