NESTJS frameworks tsconfig.json by default has a rule:
...
"declaration": true,
...
I see no usege for *.d.ts file created in /dist folder
Can I remove *.d.ts files from /dist or set
"declaration": false,
Will it cause some errors? Or "declaration": true set on purpose?
"declaration": true is useful for when you are creating npm packages to be used in typescript, which is one thing that you can do with NestJS. If you are just building a webserver however, the declaration isn't necessarily needed. Up to you if you want to keep it.
Related
I am planning to have worker threads for socket.io rooms. I create a worker thread on the first connection to a room which then sets up firebase listeners.
Unfortunately. I have common imports in the worker file and my main source code.
I followed this article to allow running ts files via worker_threads -> https://wanago.io/2019/05/06/node-js-typescript-12-worker-threads/
Unfortunately, I dont get top-level await and upon starting the worker thread, I get the following error.
error TS2451: Cannot redeclare block-scoped variable 'tslib_1'.\r\n"
Here is my tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"lib": ["esnext"],
"module": "commonjs",
"importHelpers": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"moduleResolution": "node",
"baseUrl": ".",
"sourceMap": true,
"declaration": false,
"noImplicitAny": false,
},
"files": [
"typings.d.ts"
],
}
You haven't provided any info on how you run your application, so I will suppose the following setup:
you run your main application by requiring ts-node on command line:
node -r ts-node/register index.ts
your worker entry point is a .ts file, you instantiate it as follows:
new Worker('./worker.ts')
you have the following code near the top of your worker script:
require('ts-node').register();
Assuming this is your setup, you need to remove the line
require('ts-node').register();
from your worker entry point script. This line is basically causing your TypeScript file to be compiled twice by ts-node, hence the double declaration error for tslib_1.
Registering ts-node manually like above is only necessary, when your main program wan't started with the -r ts-node/register flag. If it was, then ts-node will be automatically required when you instantiate your worker and will compile the requested TS sources on-the-fly.
There are a few other gotchas that you have to keep in mind when using workers:
The new Worker(...) API resolves the requested file relatively to your working directory, if you want to resolve relatively to the current souce file you'll need to do something like this: new Worker(path.resolve(__dirname, './worker.ts')).
If you don't use ts-node in production and instead compile your sources via tsc, you won't be able to load the worker script after your sources are compiled to JS, your worker file will become worker.js (mind the file extension). You'll need to detect this situation and change the path accordingly.
The library written in TypeScript includes three main files for distribution:
NodeJS.js - for, obviously, Node.js runtime.
BroswerJS.js - for, obviously, browser runtime.
index.js - common functionality for both browser and Node.js
There no "main" file in this library so I has not specified this property in package.json.
Planning usage:
import { isUndefined, isNull } from "package-name;
import { delegateClickEventHandling } from "package-name/BrowserJS;
import { NodeJS_Timer } from "package-name/NodeJS;
Currently, the TypeScript with below config compiles files below Source directory to Distributable directory:
{
"compilerOptions": {
"target": "ES2020",
"module": "CommonJS",
"moduleResolution": "Node",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"removeComments": true,
"outDir": "Distributable/",
"declaration": true
},
"include": [ "Source/**/*" ]
}
If to publish the library such as, TypeScript even will not see it:
import { isUndefined } from "package-name";
TS2307: Cannot find module 'package-name' or its corresponding type declarations.
Because as default TypeScript expecting that .d.ts files will be in root directory of the library. But the distributables are in Distributable directory!
And of course, isUndefined will not be found. I know about "main" property in package.json, but it is for one file case, but what about directory?
I know that multiple distributable files exporting is the supported scenario. For example the mysql2 exporting promise.ts besides index.js:
import MySQL from "mysql2";
import MySQL_Promise from "mysql2/promise";
Update
The NPM part solved - modern solution is exports filed in package.json:
"exports": {
".": "./Distributable/index.js",
"./NodeJS": "./Distributable/NodeJS.js",
"./BrowserJS": "./Distributable/BrowserJS.js"
},
But distribution files are still invisible for TypeScript.
TS2307: Cannot find module 'package-name' or its corresponding type declarations.
I learned about "types" field of package.json. Unfortunately, it could be only a string. It means currently it's impossible to specify multiple files. The issue about making in to array has been declined.
But how to make visible all of "./Distributable/index.js", "./Distributable/NodeJS.js", "./Distributable/BrowserJS.js" for TypeScript?
Please don't suggest me again to make all imports to single entry point. In this question we considering the multiple entry points case.
I am not entirely sure what you are trying to achive, in TS generally when you have single project with 1 configuration file, and you emit multiple files from it, you would not use package name within the same project, use path instead './someFileName'.
If you have multiple projects (tsconfig files) to manage different directories - sort of monorepo thing going on.
Your best options is project references: https://www.typescriptlang.org/docs/handbook/project-references.html
Or if you are doing something else then this may help altho I'd do this as last resort :-)
https://www.typescriptlang.org/tsconfig#paths
I'm converting a legacy node/express codebase to TypeScript, following the Microsoft TypeScript starter as a starting reference.
In this reference output is compiled to dist, however when enabling allowJS in tsconfig.json, the output is emitted to dist/src - why is that?
Here is my tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"moduleResolution": "node",
"sourceMap": true,
"rootDir" : "./",
"outDir": "dist",
"baseUrl": ".",
"allowJs": true,
"paths": {
"*": [
"node_modules/*",
"src/types/*"
]
}
},
"include": [
"src/**/*"
]
}
I tried changing rootDir to ./src but it gives an error saying 'node_modules/someModule' is not in the src root.
I tried moving tsconfig.json to src, according to a GitHub issue I saw, but no output was generated.
AllowJS
The output was mapping correctly under /dist until allowJS flag was turned on in tsconfig.json, after which output appeared in /dist/src
There are two things going on here:
Typescript relies on rootDir to decide the directory structure of the output (see this comment from Typescript's bossman).
Only code within the rootDir can be compiled/emitted by tsc.
If you don't set rootDir explicitly, it defaults to ./ (relative to tsconfig)... unless you've included something outside of ./ that needs to be compiled/emitted by tsc, in which case it forces rootDir to automatically get set to the directory that contains all the source.
The allowJS setting tells tsc to treat .js code as source and to also emit it to the outDir.
I suspect that when you enabled allowJS, there was .js code outside of src that tsc now had to emit to outDir, and so it automatically moved rootDir one level up. Since src is now a subdir of the rootDir, this gets mirrored within outDir.
See this answer for a solution that enables you to have src remain a rootDir and also include code from outside of it.
Sounds like your compiler (TSC) config file may be up a level from where you want the transpiler to begin the linking process. Can you try pushing it down a level and let us know what happens?
Hope this helps.
I am developing a node.js application using TypeScript.
I've created a TypeScript file in the root folder of my project. I run tsconfig and it appears to update the dist folder. However, when I run the app, I am getting an error indicating a function is not defined.
Here is where things get confusing: there seems to be older versions of the .js and .map files in my src folder in the same directories as my source files with the same names. This .js file seems to have an older version of the file missing the necessary functions (class methods), different from the current versions in my /dist folder.
At the end of the day, I am trying to run the debugger on the files in my /dist folder and set breakpoints over in my /src TypeScript files.
This is a sample of the file structure I am seeing in my /src folder (this js file is not current):
Here is a sample of the file structure of my /dist folder where the transpiled js code resides:
Also, here are the debugger settings for the web app (rest) portion of the project:
Finally, here is a sample of the tsconfig.json file:
{
"compilerOptions": {
"module": "commonjs",
"target": "ES5",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"types": ["reflect-metadata"],
"lib": ["ES6"],
"sourceMap": true,
"inlineSources": true,
"pretty": true,
"outDir": "./dist",
"rootDir": "./src/",
"noLib": false
},
"compileOnSave": true,
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"node_modules/#types"
]
}
I would like to understand what is wrong, causing it to read the wrong js files, instead of the ones in the /dist folder?
What can I do to fix this to point to the /dist folder. I thought the debugger settings I setup would do that, but this does not appear to be the case.
Update: I deleted the .js files that were generated in the src folder and they eventually returned back to the folder and once again, they were not current after making other changes. I am not sure what is generating these files; is it a setting in webstorm or is it in tsconig.json?
Something else doesn't look right. When I opened one of the files in the dist folder, I found the following code instead of JS code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=group.js.map
This is not what I was expecting, as I was expecting to see the transpiled js code.
You are declaring src in your includes and in your rootDir, everything should be declared relative to rootDir, but in this case you likely don't need the includes or excludes since you're including everything in src anyway. The compileOnSave option is what is generating the files as you delete them because a watcher has been set up to do so. You're also mixing your target and lib javascript versions.
You do not need to explicitly exclude #types if you are using the types property already.
If types is specified, only packages listed will be included.
Here's a cleaned up config you can try
{
"compilerOptions": {
"module": "commonjs",
"target": "ES5",
"moduleResolution": "node",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"types": ["reflect-metadata"],
"lib": ["ES5"],
"sourceMap": true,
"inlineSources": true,
"pretty": true,
"outDir": "dist",
"rootDir": "src",
"noLib": false
},
"compileOnSave": false
}
The whole node_modules directory can be completely excluded for TypeScript compilation using this tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"sourceMap": true,
"target": "es6"
},
"exclude": [
"node_modules"
]
}
But how can I allow one individual sub-directory under node_modules, like node_modules/app, to still get compiled? I know that the files section can be used to specify individual files and override the exclude section, but that can get unwieldy very quickly, especially when used alongside exclude. Is there a better option?
For a bit of context, I am planning to put application-specific modules in the node_modules/app directory, so I can require them without using relative paths:
var m = require("app/module1")
versus
var m = require("../../module1")).
Just require the module/subfolder that contains your code. Explicitly importing a file/directory overrides the global "exclude" in a sense that it will be picked up by tsc.
Also set "moduleResolution": "node" if you haven't already.