How to execute a command from a Typecript file? - node.js

how to execute a command from a TS file ? (not from package.json)
Here my files and my error :
src/devTools/server/tsconfig.json :
{
"compilerOptions": {
"target" : "ES2020",
"module" : "CommonJS",
},
"exclude": ["node_modules"],
"extends" : "../../../tsconfig.json", // the default config file of Create React App
}
packages.json :
"scripts": {
"test:coverage": "ts-node -r tsconfig-paths/register --project src/devTools/server/tsconfig.json --transpile-only scripts/jest/runCoverage.ts",
}
scripts/jest/runCoverage.ts:
const jestProcess = spawn('react-scripts', ['test'])
Executed command: npm run test:coverage
Actual result: error Command failed with exit code 1.
Expected result: none errors

Related

How to use import-map with Deno

I have this import_map.json file:
{
"imports": {
"node_modules/" : "./node_modules"
}
}
at a high-level I am trying to create some compatibility for .ts files, for both Deno and Node.
My imports look like this:
import * as util from 'util';
import chalk from "node_modules/chalk";
When I run this:
deno run --import-map='import_map.json' ./src/linked-queue.ts
I get this loathsome error:
Import map diagnostics:
- Invalid target address "file:///.../linked-queue/node_modules" for package specifier "node_modules/". Package address targets must end with "/".
error: Blocked by null entry for ""node_modules/""
at file:///.../linked-queue/src/linked-queue.ts:4:19
Anyone know how to resolve this error?
"imports": {
"node_modules/" : "./node_modules/"
}
Add a trailing slash on the target specifier. See also the spec and the source.
The manual covers this scenario in the following three sections:
4.1 - Using npm packages with npm specifiers
4.3 - The std/node Library
4.4 - Using Import Maps
I'll show a reproducible example rather than copy + paste everything from the docs (because a few copied snippets aren't really enough; this is a multi-faceted issue) — however take note of the values in the import map, as they are derived by reading through all three linked sections of the documentation:
./import_map.json:
{
"imports": {
"chalk": "npm:chalk#5.2.0",
"node:util": "https://deno.land/std#0.170.0/node/util.ts"
}
}
./deno.jsonc:
{
"importMap": "./import_map.json",
"tasks": {
// I included these permissions (which are required by chalk) in advance to avoid needing to grant them one-by-one at runtime:
"dev": "deno run --allow-env=FORCE_COLOR,TF_BUILD,TERM,CI,TEAMCITY_VERSION,COLORTERM,TERM_PROGRAM,TERM_PROGRAM_VERSION src/linked-queue.ts"
}
}
./src/linked-queue.ts:
import * as util from "node:util";
import chalk from "chalk";
console.log('util:', typeof util); // util: object
console.log('chalk:', typeof chalk); // chalk: function
Running in the terminal using the defined task:
% deno --version
deno 1.29.1 (release, x86_64-apple-darwin)
v8 10.9.194.5
typescript 4.9.4
% deno task dev
Task dev deno run --allow-env=FORCE_COLOR,TF_BUILD,TERM,CI,TEAMCITY_VERSION,COLORTERM,TERM_PROGRAM,TERM_PROGRAM_VERSION src/linked-queue.ts
util: object
chalk: function
% echo $?
0
So far, everything is great in Deno.
Let's check to see that the same code works without modification in Node.js. The following files need to be added to compile and run using Node, since it doesn't include all of Deno's built-in tooling:
./package.json:
{
"name": "so-74905332",
"version": "0.1.0",
"type": "module",
"scripts": {
"compile": "tsc",
"dev": "tsc && node src/linked-queue.js"
},
"license": "MIT",
"dependencies": {
"chalk": "5.2.0"
},
"devDependencies": {
"#types/node": "^18.11.17",
"typescript": "^4.9.4"
}
}
./tsconfig.json:
Why these values? I'm just using a recommended base, linked to from the TS repo wiki:
// This file was autogenerated by a script
// Equivalent to a config of: strictest extends esm extends node18
{
"$schema": "https://json.schemastore.org/tsconfig",
"display": "Node LTS + ESM + Strictest",
"_version": "18.12.1",
"compilerOptions": {
"lib": [
"es2022"
],
"module": "es2022",
"target": "es2022",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"allowUnusedLabels": false,
"allowUnreachableCode": false,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"importsNotUsedAsValues": "error",
"checkJs": true
}
}
Running in the terminal using the defined npm script:
% node --version
v18.12.1
% npm install
added 3 packages, and audited 4 packages in 1s
1 package is looking for funding
run `npm fund` for details
found 0 vulnerabilities
% npm run dev
> so-74905332#0.1.0 dev
> tsc && node src/linked-queue.js
util: object
chalk: function
% echo $?
0
The same module source code also works in Node.js.

How to setup SWC compiler

I'm using SWC for the first time and I'm not able to compile my ts files into normal js files.
When I run my command :
npx swc ./src -d dist
I got the error :
failed to process js file
Caused by:
0: failed to read swcrc file (src/index.ts)
1: failed to deserialize .swcrc (json) file: syntax error: 1:1
2: expected value at line 1 column 1
Here is my.swcrc I have generated with the SWC Playground
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": false
},
"loose": false,
"minify": {
"compress": false,
"mangle": false
}
},
"module": {
"type": "commonjs"
},
"minify": false,
"isModule": true,
"sourceMaps": "inline"
}
My goal is to :
Take my ts files from my ./src dir
Compile and output it in a dist dir with source maps enabled

How to disable react-transform-hmr in production?

I have a problem with my create react app. When I run dev version everything is fine. When I'm trying to run build version I get error:
Uncaught Error: locals[0] does not appear to be a module object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using env section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at n (react-datepicker.js:4634)
I tried this: babel.rc file
{
"presets": ["es2015", "stage-0"],
"env": {
// only enable it when process.env.NODE_ENV is 'development' or undefined
"development": {
"plugins": [[
"react-transform", {
"transforms": [{
"transform": "react-transform-hmr",
// if you use React Native, pass "react-native" instead:
"imports": ["react"],
// this is important for Webpack HMR:
"locals": ["module"]
}]
// note: you can put more transforms into array
// this is just one of them!
}
]]
}
}
}
and my build command is:
"build": "set NODE_ENV=production && react-scripts build",
Any idea why this happens or where should I look for solutions?
Thanks

Webpack/Express - environment variables not found by server

In my Express/React app, I am using Webpack to handle server-side rendering. However, I am experiencing a build error related to environment variables that I'm trying to access in my Express server script.
In the server script, index.js, I am setting a few variables like so:
const gitCommit = process.env.GIT_COMMIT || require("./gitignore/git_commit.js"),
buildDate = process.env.BUILD_DATE || require("./gitignore/build_date.js")
And since I am running a test production build on my local machine, I delete the gitignore/ directory and set those environment variables:
$ export GIT_COMMIT="test commit hash"
$ export BUILD_DATE="test build date"
Then I npm run build, which executes the following scripts:
"build:client": "webpack --config webpack.config.js",
"build:server": "webpack --config webpack.server.config.js",
"build": "npm run build:client && npm run build:server"
build:client executes with no problem, but build:server throws errors...
ERROR in ./index.js
Module not found: Error: Can't resolve './gitignore/git_commit.js' in '/Users/filepath'
# ./index.js 12:38-74
ERROR in ./index.js
Module not found: Error: Can't resolve './gitignore/build_date.js' in '/Users/filepath'
# ./index.js 13:42-78
implying that the two environment variables referenced in index.js can't be found, and so it's looking for the gitignore/ instead, which shouldn't exist (I mean, it does exist locally, but I've deleted since I'm simulating a production build).
Here is the complete webpack.server.config.js:
const fs = require("fs"),
path = require("path")// ,
// ExtractTextPlugin = require("extract-text-webpack-plugin")
module.exports = {
"entry": path.resolve(__dirname, "index.js"),
// keep node_module paths out of the bundle
"externals": fs.readdirSync(path.resolve(__dirname, "node_modules")).concat(["react-dom/server", "react/addons"]).reduce((ext, mod) => {
ext[mod] = `commonjs ${mod}`
return ext
}, {}),
"module": {
"loaders": [
{
"exclude": /node_modules/,
"loader": "babel-loader",
"query": { "presets": ["react", "es2015", "stage-2"] },
"test": /\.jsx$/
},
{
"exclude": /node_modules/,
"loader": "babel-loader",
"query": { "presets": ["react", "es2015", "stage-2"] },
"test": /\.js$/
}
]
},
"node": {
"__dirname": true,
"__filename": true
},
"output": {
"filename": "server.bundle.js"
},
"target": "node"
}
Now I expect that gitignore/ would not be found, but what I don't understand is why the two environment variables that I set are not being detected by index.js - they are definitely set in the console before I even run the build command. If I console.log() them in the beginning of webpack.server.config.js, it logs them correctly, and if I run my development version instead (which doesn't use the server config), I can log them correctly in index.js. What gives?
Node version 6.11.1, NPM version 3.10.10, Webpack version 2.6.0.
Your environment variables are only available when Webpack runs, but not when you execute your index.js.
You will need to use the EnvironmentPlugin in your Webpack config like that:
plugins: [new webpack.EnvironmentPlugin(['GIT_COMMIT ', 'BUILD_DATE'])]
That plugin will replace the variables by their actual values.
HINT: Do not use ||. Webpack does not know how to optimize it. Try the ternary operator:
const gitCommit = (process.env.GIT_COMMIT) ? (
process.env.GIT_COMMIT
) : (
require('./gitignore/git_commit.js')
);
Webpack will bundle this to:
const gitCommit = (true) ? (
"test commit hash"
) : (
require('./gitignore/git_commit.js')
);
No IgnorePlugin is needed. Even better, with the UglifyJSPlugin, your code will be optimized to const gitCommit = "test commit hash";. In some cases gitCommit is removed completely as a variable. Its string value will be used instead anywhere where you applied gitCommit.

How to use nodemon with JSX?

I can compile and run my JSX app with one command:
jsx app.jsx | node
But I also want my server to automatically restart every time I modify app.jsx. I can do that with nodemon, but I can't quite figure out how to get nodemon to run my script through the JSX compiler beforehand.
I've got a nodemon.json file set up like this:
{
"execMap": {
"js": "node",
"jsx": "jsx {{filename}} | node"
},
"ext": "js jsx",
"ignore": [
".hg",
"node_modules",
".idea"
],
"verbose": true
}
But when I run nodemon it tells me:
8 Feb 21:58:48 - [nodemon] starting `jsx app.jsx | node`
8 Feb 21:58:48 - [nodemon] child pid: 10976
'\"jsx app.jsx | node\"' is not recognized as an internal or external command,
operable program or batch file.
Which is odd, because that command works verbatim when I paste it directly into my terminal.
Is there any way I get nodemon to run my JSX files?
It seems nodemon is attempting to run a program with the name you provide, rather than executing a shell.
Create a jsx.sh file with this content:
#!/bin/sh
jsx "$1" | node
Then chmod +x jsx.sh, and put this in your nodemon.json:
{
"execMap": {
"js": "node",
"jsx": "./jsx.sh"
},
"ext": "js jsx",
"ignore": [
".hg",
"node_modules",
".idea"
],
"verbose": true
}
* not tested
OR you can just locate the jsx command in your ./node_modules/.bin directory and run it off that instead:
{
script: "client.js",
options: {
execMap: {
"js": "node",
"jsx": "./node_modules/.bin/jsx \"$1\" | node"
},
ext: "js jsx",
callback: function (nodemon) {
nodemon.on("log", function (event) {
console.log(event.colour);
});
},
ignore: [
"node_modules/**/*.js",
"public/js/**",
"lib/api/**",
]
}
}
If you're on Windows (like me) you can create a .bat instead of a .sh like FakeRainBrigand suggests
#echo off
jsx %1 | node
This file has to be in the same directory as nodemon.json and package.json -- paths don't seem to work in the execMap for whatever reason.
Also, an even easier solution is to just not use any JSX in your main/server script, install node-jsx and then require your JSX files as needed.

Resources