How to specify or override TypeScript config in Deno - deno

I'm starting out on a new Deno project and ran into errors
const users = [
{ name: 'Oby', age: 12 },
{ name: 'Heera', age: 32 },
];
const loggedInUser = users.find((u) => u.name === 'Oby');
console.log(loggedInUser.age);
$ deno run hello.ts
Compile file:///Users/yangshun/Downloads/deno-test/hello.ts
error: TS2532 [ERROR]: Object is possibly 'undefined'.
console.log(loggedInUser.age);
This is caused by "strictNullChecks": true in the TypeScript config. Hence I would like to use my own tsconfig.json (TypeScript configuration) but am not sure how to go about doing so.

Create a tsconfig.json file.
{
"compilerOptions": {
"strictNullChecks": false
}
}
Execute the deno run with the -c configuration argument.
$ deno run -c tsconfig.json hello.ts
Compile file:///Users/yangshun/Downloads/deno-test/hello.ts
12

Related

How can I get Vite env variables?

I am using Quasar, Vue 3, Vite, Cypress in my project. I don't know how to get .env variables (e.g. VITE_API_URL) and to set in cypress.env.json. Before Vite I used webpack and I know how to do it.
I don't want to define twice same variable, first in .env then in cypress.env.json.
You can use the dotenv package directly, merging the result in with the env section of your cypress config.
.env
VITE_API_URL: "http://example.com"
cypress.config.js
const { defineConfig } = require("cypress");
const dotenv = require('dotenv')
const env = dotenv.config('./.env').parsed
module.exports = defineConfig({
'component': {
// component config here
},
env: {
login_url: '/login',
...env, // merge here with spread operator
},
});
Settings page in the Cypress runner
env: {
login_url: '/login',
VITE_API_URL: 'http://example.com',
},
There is a plugin called cypress-dotenv for this very purpose. It allows you to share your .env file variables between your app and cypress tests.
Install
npm install --save-dev cypress-dotenv
# For typescript
npm install --save-dev #types/cypress-dotenv
Example
Example .env file
VITE_API_URL=https://vite-api-url.com
In your cypress.config.js, run the plugin dotenvCypress() under setupNodeEvents():
import { defineConfig } from "cypress";
import dotenvCypress from 'cypress-dotenv';
export default defineConfig({
component: {
devServer: {
framework: "vue",
bundler: "vite",
},
setupNodeEvents(on, config) {
return dotenvCypress(config, undefined, true);
},
},
});
Then in your test:
it('works', () => {
cy.log(Cypress.env('VITE_API_URL'));
});
Notes
dotenvCypress() must be returned in setupNodeEvents()
To get all the env variables from your .env file, you have to pass true as the third argument to dotenvCypress(). Otherwise, only vars prefixed with CYPRESS_ will be available.
https://www.npmjs.com/package/cypress-dotenv

How do you shim react-pdf with esbuild?

If you bundle react-pdf for the browser using esbuild today you will run into errors that prompt you to build for platform=node because zlib and stream are not available in the browser environment.
I did find a conversation around how to swap this when using vite but I'm curious if others have created a shim for esbuild that offers something equivalent
process: "process/browser",
stream: "vite-compatible-readable-stream",
zlib: "browserify-zlib"
the version I'm using today: #react-pdf/renderer": "^2.0.21"
edit
It just so happens a node modules polyfill exists for esbuild and you should be able to configure this as a plugin
https://github.com/remorses/esbuild-plugins#readme
npm i -D #esbuild-plugins/node-globals-polyfill
and then w/ esbuild you can pass it in like so
https://esbuild.github.io/plugins/#using-plugins
More after I confirm this is working end to end
I was able to achieve this using esbuild v0.14.10 and 2 plugins
npm i -D #esbuild-plugins/node-modules-polyfill
npm i -D #esbuild-plugins/node-globals-polyfill
With a build configuration like this
const esbuild = require('esbuild')
const globalsPlugin = require('#esbuild-plugins/node-globals-polyfill')
const modulesPlugin = require('#esbuild-plugins/node-modules-polyfill')
const args = process.argv.slice(2)
const deploy = args.includes('--deploy')
const loader = {
// Add loaders for images/fonts/etc, e.g. { '.svg': 'file' }
}
const plugins = [
globalsPlugin.NodeGlobalsPolyfillPlugin({
process: true,
buffer: true,
define: { 'process.env.NODE_ENV': deploy ? '"production"' : '"development"' },
}),
modulesPlugin.NodeModulesPolyfillPlugin(),
]
let opts = {
entryPoints: ['js/app.js'],
bundle: true,
target: 'es2017',
outdir: '../priv/static/assets',
logLevel: 'info',
inject: ['./react-shim.js'],
loader,
plugins
}
if (deploy) {
opts = {
...opts,
minify: true
}
}
const promise = esbuild.build(opts)

Deno cotton 'must have type'

I'm following a course on Deno and Angular but I am stuck. I have even downloaded the final code supplied by the person who created the course and get the same type of error.
When I try and run this commmand: deno run --allow-net --unstable app.ts
I keep getting this error message:
Check file:///?:/????/deno-admin-main/app.ts
error: Uncaught Error: Column 'role_id' must have a type!
throw new Error(Column '${propertyKey}' must have a type!);
^
at https://deno.land/x/cotton#v0.7.5/src/model.ts:76:13
at DecorateProperty (https://deno.land/x/cotton#v0.7.5/src/utils>/reflect.ts:1431:27)
at Reflect.decorate (https://deno.land/x/cotton#v0.7.5/src/utils/reflect.ts:858:16)
at __decorate (file:///?:/????/deno-admin-main/src/models/role-permission.ts:3:92)
at file:///?:/????/deno-admin-main/src/models/role-permission.ts:9:5
// role-permission
import {Model, Primary, Column} from "https://deno.land/x/cotton#v0.7.5/mod.ts";
#Model('role_permissions')
export class RolePermission {
#Primary()
id!: number;
#Column()
role_id!: number;
#Column()
permission_id!: number;
}
According to their docs the use of this cotton feature requires a custom tsconfig.json to be included when running the program:
Keep in mind that this feature requires a custom TypeScript configuration to tell Deno that we want to use TypeScript decorators (opens new window), which is currently still an experimental feature.
// tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
deno run --unstable --config ./tsconfig.json app.ts
The problem was a typo. I did not add "app.ts" to the file scripts.json:
{
"$schema": "https://deno.land/x/denon#2.4.7/schema.json",
"scripts": {
"start": {
"cmd": "deno run app.ts",
"desc": "run my app.ts file",
"allow": [
"net"
] ,
"tsconfig": "tsconfig.json"
}
},
"watcher": {
"match": [
"app.ts",
"src/**/*.ts"
]
}
}

How to use TS Path Mapping with Firebase Cloud Functions

How do I use TS Path Mapping with Firebase Cloud Functions?
I tried without success:
"baseUrl": ".",
"paths": {
"#custom-path/*": ["src/utils/*"],
"#other-path/*": ["../other/path/*"]
}
Finally I was able to do this with module-alias NPM package.
Install it as non-dev dependency: yarn add module-alias #types/module-alias
Create a file fixTsPaths.ts or whatever with content like this:
import * as ModuleAlias from 'module-alias';
ModuleAlias.addAliases({
'common': __dirname + '/../../../common',
});
Here's the trick about the path /../../../common: in my case this folder is outside functions, and Typescript replicates folders structure during the build, so that's could be the reason why https://github.com/dividab/tsconfig-paths was not working out of the box. So in every case one needs to check this path and find appropriate '..' count :)
And finally import this file in your index.ts at the very top:
import './fixTsPaths';
Hope this helps!
It's 2022 and the neatest way to do this is to use tsc-alias.
On tsconfig.json, add baseUrl and add your paths under compilerOptions. Something like:
{
"compilerOptions": {
...
"baseUrl": "./src",
"paths": {
"#constants/*": ["api/constants/*"],
"#interfaces/*": ["api/interfaces/*"],
"#middlewares/*": ["api/middlewares/*"],
"#modules/*": ["api/modules/*"],
"#services/*": ["api/services/*"]
},
...
}
Then, change your serve and build scripts, under package.json. Like:
...
"scripts": {
"build": "tsc && tsc-alias",
"build:watch": "concurrently \"tsc -w\" \"tsc-alias -w\"",
"serve": "concurrently --kill-others \"firebase emulators:start --only functions\" \"npm run build:watch\"",
...
},
...
☝️ here I'm using concurrently, but feel free to use whatever you like.
And that's it. You can now import stuff using your defined paths, like:
import { messages } from '#constants/responses'
import CandidatesService from '#modules/candidates/candidates.service'
import { IModule } from '#interfaces/module.interface'
etc...
The problem is the rule no-implicit-dependencies: true on the tslint.json. You can pass additional params to whitelist your custom paths:
"no-implicit-dependencies": [true, ["#custom-path", "#other-path"]],
for anyone who still struggles with this issue, but the below code at the top of the entry point file (main.ts).
don't forget to adjust the tsconfig.json file path if it is not in the default location
const tsConfig = require('../tsconfig.json');
const tsConfigPaths = require('tsconfig-paths');
tsConfigPaths.register({
baseUrl: __dirname,
paths: tsConfig.compilerOptions.paths,
});
I was able to do this with #zerollup/ts-transform-paths NPM package.
Install #zerollup/ts-transform-paths as dev dependency: yarn add -D #zerollup/ts-transform-paths
Setup following config of webpack + ts-loader.
const tsTransformPaths = require('#zerollup/ts-transform-paths');
module.exports = {
... // other config
module: {
rules: [
{
test: /\.(ts|tsx)$/,
loader: 'ts-loader',
options: {
getCustomTransformers: (program) => {
const transformer = tsTransformPaths(program);
return {
before: [transformer.before], // for updating paths in generated code
afterDeclarations: [transformer.afterDeclarations] // for updating paths in declaration files
};
}
}
}
]
}
};
See more in detail: https://github.com/zerkalica/zerollup/tree/5aee60287647350215c81d0b2da5a30717d9dccb/packages/ts-transform-paths

Warning: connect.static is not a function Use --force to continue

I am using YO lessapp project, "grunt-contrib-connect" helps me to start a node js server on 9000 port. Whenever I run grunt serve (start the server) the service is aborted due to the below warning.
Running "connect:livereload" (connect) task
Warning: connect.static is not a function Use --force to continue.
The exact error took place in the below function in Gruntfile.js
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
I have installed
npm install grunt-contrib-connect --save-dev,
npm install serve-static --save-dev
I came across few post, some suggest to turn off the firewall but no luck.
I know there is something to do with my machine or npm/node/connect version conflicts, because I tried to run the same app from other machine and it works fine.
System configuration :
Windows 7 Professional
Node -v4.1.2
npm -v2.14.4
connect#3.4.0
I have installed connect and serve-static based upon the post nodejs connect cannot find static, but still the same
Any help? Thanks in Advance
You have to install connect and serve-static:
npm install --save-dev grunt-contrib-connect serve-static
And then you have to import serve-static in Gruntfile.js:
module.exports = function (grunt) {
...
var serveStatic = require('serve-static');
grunt.initConfig({
...
connect: {
...
livereload: {
options: {
middleware: function(connect) {
return [
serveStatic('.tmp'),
connect().use('/bower_components', serveStatic('./bower_components')),
serveStatic(config.app)
];
}
}
}
From version 0.11.x, the new grunt-contrib-connect does not support connect.static and connect.directory.
You should install serve-static(for serve static files) and serve-index (for Serves pages that contain directory listings for a given path).
like this:
var serveStatic = require('serve-static');
var serveIndex = require('serve-index');
Use serveStatic instead connect.static
and
serveIndex instead connect.directory
grunt.initConfig({
connect: {
options: {
test: {
directory: 'somePath',
middleware: function(connect, options){
var _staticPath = path.resolve(options.directory);
return [serveStatic(_staticPath), serveIndex(_staticPath)]
}
}
}
}
})

Resources