How to setup SWC compiler - node.js

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

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.

Error [ERR_REQUIRE_ESM] - Husky, lint-staged, eslint - nodeJS:

although there were other questions about this, most were left without a response or the response given did not work for me.
For what it gives apparently eslint is looking within node_modules, here is the given error:
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/kamoraes/Workspace/node_adc/node_modules/supports-color/index.js from /home/kamoraes/Workspace/node_adc/.git/hooks/commit-msg not supported.
Instead change the require of index.js in /home/kamoraes/Workspace/node_adc/.git/hooks/commit-msg to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/home/kamoraes/Workspace/node_adc/.git/hooks/commit-msg:8:23) {
code: 'ERR_REQUIRE_ESM'
}
Node v16.13.0
The problem is, the project is in it's first steps, quickly redoing the project in another machine on the same node and yarn, version, don't give the same error. Also asked a friend of mine to try it. no error given.
also, this project is an course, same steps made, here is my entire code as for now:
https://github.com/kaiqueAMoraes/clean-node-api
the last commit for this given error is chore: eslintignore 6250e5bdea05cc2eb413c8a57a97e4bbe4bd5bb9
I've added husky, lint-staged
yarn add -D husky lint-staged
then added their respectively config files
.huskyrc.json:
{
"hooks": {
"pre-commit": "lint-staged"
}
}
.lintstagedrd.json:
{
"*.ts": [
"eslint 'src/**' --fix",
"git add"
]
}
for reference:
tsconfig:
{
"compilerOptions": {
"outDir" : "./dist",
"module": "commonjs",
"target": "es2019",
"strictNullChecks": true,
"esModuleInterop": true,
"allowJs": true
}
}
eslintrc:
{
"extends": "standard-with-typescript",
"parserOptions": {
"project": "./tsconfig.json"
}
}
both gitignore and eslintignore ignores node_modules and dist
Ran into the same issue.
You could bypass the check with git commit -m "your message here" --no-verify.

How to execute a command from a Typecript file?

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

jest cannot resolve module aliases

I am using a npm module called module-alias. I map some modules in tsconfig.json and package.json
tsconfig.json
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#config/*": ["config/*"],
"#interfaces/*": ["interfaces/*"],
"#services/*": ["services/*"]
},
"module": "commonjs",
"target": "es2015", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
"sourceMap": true,
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src",
"allowSyntheticDefaultImports": true /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
}
package.json
...
"_moduleAliases": {
"#config": "src/config",
"#interface": "src/interface",
"#services": "src/services"
},
"jest": {
"moduleNameMapper": {
"#config/(.*)": "src/config/$1",
"#interface/(.*)": "src/interface/$1",
"#services/(.*)": "src/services/$1"
},
"moduleFileExtensions": ['js', 'json', 'jsx', 'ts', 'tsx', 'node']
},
...
server.ts
import { logger } from '#config/logger';
everything works fine when I run npm start, but it gives me an error when I run jest
FAIL src/test/article.spec.ts
● Test suite failed to run
Cannot find module '#config/logger' from 'server.ts'
However, Jest was able to find:
'rest/server.ts'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'json', 'jsx', 'ts', 'tsx', 'node'].
Anyone know what the problem is? thanks
Solution works for me (Update 18/10/2019) :
Create a jest.config.js with code below:
module.exports = {
"roots": [
"<rootDir>/src/"
],
"transform": {
"^.+\\.tsx?$": "ts-jest"
}
}
and update moduleNameMapper in package.json:
...
"_moduleAliases": {
"#config": "./src/config",
"#interfaces": "./src/interfaces",
"#services": "./src/services"
},
"jest": {
"moduleNameMapper": {
"#config/(.*)": "<rootDir>/src/config/$1",
"#interfaces/(.*)": "<rootDir>/src/interfaces/$1",
"#services/(.*)": "<rootDir>/src/services/$1"
}
}
...
After a few hours I've managed to make this work. I'll try my best to simplify it to save others time and make it smooth.
My app is of the following stack:
Typescript (tsc and ts-node/register, no Babel) for the API build (.ts)
React (.tsx using Webpack)
jest for API testing (no Babel)
testcafe for UI/E2E
VSCode as IDE
Key notes:
The solution that works for me is must have "#" character in front of the alias. It's not required in theory by module-alias, however Jest is getting lost when we apply the module name mapper.
There needs to be consistency for naming between 'webpack' aliases and 'tsconfig'. It is necessary for VSCode not to red underline module names in TSX files.
This should work regardless of your document structure but remember to adapt baseUrl and jest config if encounter issues.
When applying changes in VSCode for .tsx files do not be worried that some of the paths are underlined. It's temporary as VSCode seems to grasp it only when all files are correctly connected to each other. It demotivated me at the start.
First, install module-alias from https://www.npmjs.com/package/module-alias with
npm i --save module-alias
then add to your initial startup file (for .ts files only, i.e. your application server):
require('module-alias/register')
as the module-alias docs indicate. Then setup tsconfig.ts. Keep it mind that baseUrl is relevant here as well:
{
"compilerOptions": {
"baseUrl": ".",
...
"paths": {
"#helpers/*": ["src/helpers/*"],
"#root/*": ["src/*"]
...
}
}
then setup your webpack.js:
const path = require('path')
...
{
resolve: {
...
alias: {
'#helpers': path.resolve(__dirname, 'src', 'helpers'),
'#root': path.resolve(__dirname, 'src')
}
}
}
then setup your package.json:
{
...
"_moduleAliases": {
"#helpers": "src/helpers",
"#root": "src"
}
}
then setup your jest config (I attach only things that were relevant when applying my change):
{
rootDir: ".",
roots: ["./src"],
transform: {
"^.+\\.ts?$": "ts-jest"
},
moduleNameMapper: {
"#helpers/(.*)": "<rootDir>/src/helpers/$1",
"#root/(.*)": "<rootDir>/src/$1"
},
...
}
Now, we need to take care of the build process because tsc is not capable of transpiling aliases to their relative siblings.
To do that we will use tscpaths package: https://github.com/joonhocho/tscpaths . This one is simple.
So considering your build command was just:
tsc
Now it becomes
tsc && tscpaths -p tsconfig.json -s ./src -o ./dist/server
You need to adjust your -s and -o to your structure, but when you inspect your .js file after build you should see if the relative path is correctly linked (and debug accordingly).
That's it. It should work as ace. It's a lot but it's worth it.
Example of a call in the controller (.ts) and in React component (.tsx) file:
import { IApiResponse } from '#intf/IApi'
In my case to support #Greg Wozniak's answer, I only needed to fix my jest config file.
My app uses jest.config.ts
In my src/index.ts I have import "module-alias/register"
In package.json:
{
...
"_moduleAliases": {
"#helpers": "dist/helpers",
"#root": "dist"
}
}
In tsconfig.json:
{
"compilerOptions": {
"baseUrl": "./src",
...
"paths": {
"#helpers/*": ["helpers/*"],
"#root/*": ["*"]
...
}
}
In jest.config.ts:
added roots, preset, the (.*) and $1 signs in moduleNameMapper*
{
roots: [
"<rootDir>/src/"
],
preset: "ts-jest",
transform: {
"^.+\\.(ts|tsx)$": "ts-jest",
},
moduleNameMapper: {
"#helpers/(.*)": "<rootDir>/src/helpers/$1",
"#root/(.*)": "<rootDir>/src/$1"
},
...
}
I think you don't have the routes properly configured in your tsconfig, since the paths lack the src folder (while they appear in your package.json module alias config):
Your tsconfig code:
"#config/*": ["config/*"],
"#interfaces/*": ["interfaces/*"],
"#services/*": ["services/*"]
How I think it should be:
"#config/*": ["src/config/*"],
"#interfaces/*": ["src/interfaces/*"],
"#services/*": ["src/services/*"]

sublime text3 jshint error "Incompatible values for 'undefined' and 'undefined' linting options." when using IIFE expression

OS: macOS Sierra 10.12.5 .
Sublime Text: Build 3126 .
jshint v2.9.5 .
eslint v4.4.0 .
I have installed below packages for linting the js file
sublimeLinter-contrib-eslint
sublimeLinter-jshint
In my each .js file, IIFE (function(){ has been written on the top of the file BUT linter gives below error in gutter
Incompatible values for "undefined" and "undefined" linting options.
I have both .jshintrc and .eslintrc file in my project root directory BUT I am a bit confused
1. Which linter throw this error? and
2. How to resolve/fix it?
-.jshintrc_
{
"node": true,
"esversion": 6,
"globals" : {
"moment": true,
"saveAs": true
}
}
.eslintrc
{
"env": {
"browser": true,
"node": true,
"es6": true
},
"extends": "eslint:recommended",
"globals": {
"angular": true,
"module": true,
"inject": true,
"moment": true,
"saveAs": true,
"AWS": true,
"require": false
},
"rules": {
"indent": [0,"tab"],
"linebreak-style": [0, "unix"],
"semi": [2, "always"]
}
}
JS file
(function() {
'use strict';
angular.module().controller(function () { //....code.... });
})();
I have tried the rules as per eslint documentation
"rules": {
"wrap-iife": [2, "outside"]
}
tried all possible values but did not succeed.
Found solution by using Debug mode for sublimeLinter.
there are mixing of 2 .jshintrc files. one is the default ( which can be viewed by (context menu > JSHint > Set Linting Preferences ) and other is custom .jshintrc which located in my project root directory and also there are 2 property esnext and esversion written which I think is not valid. from this refrence
so first clear all comments from default .jshintrc (/Users//Library/Application Support/Sublime Text 3/Packages/JSHint Gutter/.jshintrc) and remove esversion property from custom .jshintrc file and everything is working fine now.

Resources