unexpected identifier in .d.ts file - javascript

I am using typescript with the following build instructions.
"build:types": "tsc --emitDeclarationOnly",
"build:js": "babel src --out-dir lib --extensions \".ts,.tsx\" --source-maps inline",
"start": "npm run build:types && npm run build:js && node ./lib/bin/www.js"
One of my .ts files imports mongoose. When running npm start I get the following error. in the .d.ts file
\lib\models\v1\collection1.model.d.ts:1
(function (exports, require, module, __filename, __dirname) { import mongoose from 'mongoose';
^^^^^^^^
SyntaxError: Unexpected identifier
note "#types/mongoose" and "mongoose" are dependence already.
the content of collection1.model.d.ts is as follows. which is generated by tsc --emitDeclarationOnly
import mongoose from 'mongoose';
declare const _default: mongoose.Model<mongoose.Document, {}>;
export default _default;
tsconfig.json
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"declaration": true,
"outDir": "./lib",
"strict": false,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
},
"include": ["src"]
}
.babelrc
{
"presets": [
"#babel/env",
"#babel/typescript"
],
"plugins": [
"#babel/proposal-class-properties",
"#babel/proposal-object-rest-spread",
"#babel/transform-runtime"
]
}

So the problem is I should have not used babel and instead simply use tsc to generate all the code. Thank you to all that helped

Related

Typescript baseUrl not resolving in build folder

I have a simple Typescript node app that works in dev mode but when I run a build, it doesn't seem to convert the baseUrl and paths correctly.
// index.ts
import config from "#/config"; // this lives in `src/config.ts`
console.log("config:", config)
My tsconfig is as follows:
{
"compilerOptions": {
"skipLibCheck": true,
"target": "es2021",
"esModuleInterop": true,
"resolveJsonModule": true,
"module": "CommonJS",
"moduleResolution": "node",
"strict": false,
"outDir": "dist",
"baseUrl": "./src",
"paths": {
"#/*": ["*"]
}
},
"include": ["src/**/*", "integration/**/*", "src/types.d.ts", "./global.d.ts"]
}
I can then run a successful npm run build but then running npm run start throws an error: Error: Cannot find module '#/config'. When I check the build file, it is still showing the imports / requires with # in them like so:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const config_1 = __importDefault(require("#/config")); // I believe this should be the relative path
console.log("config:", config_1.default);
My NPM scripts are as follows:
{
"scripts": {
"build": "NODE_ENV=production && tsc --project tsconfig.build.json",
"dev": "nodemon -r tsconfig-paths/register -r dotenv/config --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
"start": "NODE_ENV=production node dist/index.js"
}
}
How do I configure Typescript to convert my imports to replace the baseUrl paths to the correct ones that Javascript will understand?

Conflict between baseUrl and node_modules when importing

I have a TS project with the following configuration:
tsconfig.json (partial)
{
"compilerOptions": {
"module": "commonjs",
"baseUrl": "src",
"esModuleInterop": true,
},
"include": [
"src"
]
}
I have a dependency on the stripe NPM package:
{
// ...
"dependencies": {
"stripe": "^8.45.0",
}
}
Then I have the following files:
src/routes/payments/index.ts
src/stripe/index.ts
I am having some trouble with imports in src/routes/payments/index.ts. I want to import the stripe library, not my own code.
This works:
// Uses me the 'Stripe' constructor which is the default export from the package
const stripe = require('stripe')('KEY');
This does not work:
import Stripe from 'stripe';
const stripe = new Stripe('KEY');
I get the following error:
Module '"PROJECT/src/stripe/index"' has no default export.
How do I disambiguate and tell TS I want to use stripe from node_modules?
Can you try to update the tsconfig.json file like this:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"baseUrl": ".",
"paths": {
"*": [
"node_modules/*",
"src/*"
]
}
}
}

tsconfig path cannot be found

I am working on a nodejs app and I want to configure my path in tsconfig.json but I am having issues with the path configuration I keep getting an error Error: Cannot find module '#environment'. what could be the issue?
tsconfig
{
"compilerOptions": {
"resolveJsonModule" : true,
"target": "es6",
"module": "commonjs" ,
"lib": [
"dom",
"es6"
],
"outDir": "build",
"rootDir": "src",
"removeComments": true ,
"strict": true,
"noImplicitAny": true,
"baseUrl": "./",
"paths": {
"#lime/*": ["src/*"],
"#environment": ["src/config/environment.ts"],
},
"esModuleInterop": true
}
}
Project tree:
src - config - environment.ts
...
- index.js
package.json
tsconfig.json
...
environment.ts
import * as dotenv from 'dotenv';
dotenv.config();
interface Environment {
port: number | string,
baseUrl: string,
databaseUri: string,
}
export const environment: Environment = {
port: process.env.PORT!,
baseUrl: process.env.BASE_URL!,
databaseUri: process.env.DATABASE_URI!
}
in index.ts i imported environment.ts as import { environment } from '#environment'; please what could be wrong?
If you are trying to execute this directly with node or ts-node, you should be aware that tsconfig paths are not resolved by default by node. If you are using tsc for the build (and not webpack or similar to generate a bundle), you can add to your dependencies tsconfig-paths like this:
npm install --save tsconfig-paths
And then execute the code with:
node -r tsconfig-paths/register dist/index.js
If you are using TS code directly with ts-node, you can use:
ts-node -r tsconfig-paths/register src/index.ts
In production is suggested instead to bundle the source with webpack for example, and use a plugin like tsconfig-paths-webpack-plugin) to resolve paths while bundling.
I may not sure, i check the documentation. Seems like paths should be dir. please try this combination.
{
"baseUrl": "./",
"paths": {
"#lime/*": ["src/*"],
"#environment": ["src/config/"],
},
"esModuleInterop": true
}
}
and import like:
import { environment } from '#environment/environment'
tsconfig.json
// prettier-ignore
{
"extends": "#tsconfig/react-native/tsconfig.json", /* Recommended React Native TSConfig base */
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Completeness */
"skipLibCheck": true, /* Skip type checking all .d.ts files. */
/* Path */
"baseUrl": "./src",
"paths": {
"#/*": ["./*"],
"#assets/*": ["assets/*"],
"#components/*": ["components/*"],
"#hooks/*": ["hooks/*"],
"#lib/*": ["lib/*"],
"#ui/*": ["ui/*"],
}
},
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
babel.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./src'],
extensions: [
'.ios.ts',
'.android.ts',
'.ts',
'.ios.tsx',
'.android.tsx',
'.tsx',
'.jsx',
'.js',
'.json',
],
alias: {
'#': './src',
'#assets': './src/assets',
'#components': './src/components',
'#hooks': './src/hooks',
'#lib': './src/lib',
'#ui': './src/ui',
},
},
],
],
};

How to set alias path via webpack in CRA (create-react-app) and craco?

I have a problem on set webpack alias path using create-react-app and craco, already googling it but can't solve the problem.
I got an error Module not found: Can't resolve '#app/App' in 'C:\ReactSandbox\my-project\src everytime i run application using command yarn start
Steps to reproduce:
create-react-app my-project
cd my-project
yarn add #craco/craco
cat > craco.config.js (see configuration below)
replace react-scripts to craco on 'script' section on package.json (craco start, craco build, etc)
edit file src/index.js (replace line 4, see code below)
yarn start
craco.config.js
const path = require("path");
module.exports = {
webpack: {
resolve: {
alias: {
"#app": path.resolve(__dirname, "src/"),
}
}
}
};
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from '#app/App'; //replace './App' into '#app/App'
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
Current result
Module not found: Can't resolve '#app/App' in 'C:\ReactSandbox\my-project\src
Expected
I'm avoiding call relative path hell, instead of import module like ../../../../FilterComment.js, it would be clean to write #app/FilterComment.js
resolve for carco:
u need install craco-alias, then will write in
craco.config.js
const CracoAlias = require('craco-alias')
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: 'tsconfig',
baseUrl: '.',
tsConfigPath: './tsconfig.path.json',
},
},
],
}
tsconfig.path.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#/*": ["src/*"],
"#svg/*": ["src/assets/svg/*"],
"#img/*": ["src/assets/images/*"],
"#icons/*": ["src/assets/icons/*"],
"#shared/*": ["src/shared/*"],
"#components/*": ["src/components/*"],
"#hooks/*": ["src/hooks/*"],
"#constants/*": ["src/constants/*"],
"#layout/*": ["src/layout/*"],
"#services/*": ["src/services/*"]
}
}
}
tsconfig.json
{
"extends": "./tsconfig.path.json",
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"checkJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true,
"removeComments": true
},
"include": [
"src",
"src/configs",
"react-app-env.d.ts"
]
}
First - tell to IDE about aliases in tsconfig.json:
create separate file tsconfig.paths.json and add aliases:
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"#utils/*": ["utils/*"]
}
}
}
Add created tsconfig.paths.json to main tsconfig.json
{
"extends": "./tsconfig.paths.json",
... other staff ...
}
Second - tell to webpack about aliases:
Add aliases to config-overrides.js
const {
override,
addWebpackAlias
} = require('customize-cra');
const path = require("path");
module.exports = override(
addWebpackAlias({
"#utils": path.resolve(__dirname, "./src/utils"),
}),
);
my craco.config.js look likes below, it works:
const path = require('path');
module.exports = {
// ...
webpack: {
alias: {
'#': path.join(path.resolve(__dirname, './src')),
}
}
}
Just keep your file craco.config.js just like this, and you need to add 1 more file with named jsconfig.json
it's content:
{
"compilerOptions": {
"module": "commonjs",
"target": "es2016",
"jsx": "preserve",
"checkJs": true,
"baseUrl": "./src/",
"paths": {
"#app/*": ["./*"]
}
},
"exclude": ["node_modules", "**/node_modules/*"]
}
then you can import from the absolute path like #app/FilterComment.js
It also worked for VSCode (editor now understand where #app point to).
But if you want VSCode to do the import automatically, then you should add more config for it to force it always do the import from absolute path.
file .vscode/settings.json
content:
{
"javascript.preferences.importModuleSpecifier": "non-relative"
}
An example (which I'm using) without using dependency:
//craco.config.js
const path = require('path')
const tsconfig = require('./tsconfig.base.json')
const removeAsterisk = path => path.replace('/*', '')
const aliasProps = Object.entries(tsconfig.compilerOptions.paths).map(([key, value]) => {
const newKey = removeAsterisk(key)
let newValue = removeAsterisk(value[0])
newValue = path.resolve(__dirname, newValue)
return [newKey, newValue]
})
const alias = Object.fromEntries(aliasProps)
module.exports = {
webpack: {
alias,
},
}
//tsconfig.base.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"~/*": ["./src/*"],
//...
}
}
}
// tsconfig.json
{
"extends": "./tsconfig.base.json",
"compilerOptions": {/*...*/}
}
Use react-app-alias:
Install craco and react-app-alias and create craco config:
// craco.config.js
const {CracoAliasPlugin} = require('react-app-alias')
module.exports = {
plugins: [
{
plugin: CracoAliasPlugin,
options: {}
}
]
}
Replace react-scripts with craco in package.json.
Create typescript config and alias in separated config like this:
// tsconfig.paths.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"example/*": ["example/src/*"],
"#app/*": ["app/src/*"]
}
}
}
// tsconfig.json
{
"extends": "./tsconfig.paths.json",
// ...
}
Now you can do import like this:
import App from '#app/App'
Maybe the OP had a different version of React / Webpack (I'm using today's current versions), but putting the alias object directly inside the webpack object (without nesting it in the resolve object) did the trick for me:
const path = require("path");
module.exports = {
webpack: {
alias: {
"#app": path.resolve(__dirname, "src"),
}
}
};
I am using craco-alias plugin for automatic aliases generation for Webpack and Jest.
(I am just an intern but that's how senior developers in my company are using absolute imports in react)
Install
yarn add #craco/craco
yarn add craco-alias
craco.config.js
const CracoAlias = require('craco-alias');
module.exports = {
plugins: [
{
plugin: CracoAlias,
options: {
source: 'tsconfig',
baseUrl: './src',
tsConfigPath: './tsconfig.paths.json', // or wherever you have defined your paths
},
},
],
};
And make sure that you scripts in package.json look like the following
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "craco eject",
...
},
Then It'll work as specified in tsconfig.json.
FYI I have,
"react-scripts": "4.0.3"
"#craco/craco": "^6.3.0"
"craco-alias": "^3.0.1"

tsc compile import with wrong path, adding index at the end of #angular/material

I am trying to buiding a library to agregate and distribute a set of angular components between multiple projects, with a dependancy on angular/material2. My goal is to publish it in npm.
Having an issue when running tsc to package the lib, .js file try to import from '#angular/material/index'. Same file .d.ts import from '#angular/material' and I do not understand where this difference is coming from.
My gulp :
import {main as tsc} from '#angular/tsc-wrapped';
const libraryRoot = join('/../myproject/src', 'lib');
const tsconfigPath = join(libraryRoot, 'tsconfig.json');
task('library:build:esm', () => tsc(tsconfigPath, {basePath: libraryRoot}));
My tsconfig :
{
"compilerOptions": {
"baseUrl": ".",
"declaration": false,
"stripInternal": false,
"experimentalDecorators": true,
"module": "es2015",
"moduleResolution": "node",
"outDir": "../../dist/packages/mila-angular",
"paths": {},
"rootDir": ".",
"sourceMap": true,
"inlineSources": true,
"target": "es2015",
"lib": ["es2015", "dom"],
"skipLibCheck": false,
"types": [
]
},
"files": [
"public-api.ts",
"typings.d.ts"
],
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"strictMetadataEmit": true,
"flatModuleOutFile": "index.js",
"flatModuleId": "mila-angular",
"skipTemplateCodegen": true
}
}
myComponent.ts
import { MdDialog, MdDialogRef } from '#angular/material';
myComponent.d.ts
import { MdDialog, MdDialogRef } from '#angular/material';
myComponent.js
import { MdDialog, MdDialogRef } from '#angular/material/index';
As a result, when importing my library I have the following error message :
import { ButtonModule } from 'myLibrary';
ERROR in ./~/myLibrary/myLibrary.es5.js
Module not found: Error: Can't resolve '#angular/material/index' in '/.../myProject/node_modules/myLibrary'
# ./~/myLibrary/myLibrary.es5.js 8:0-80
# ./src/app/app.module.ts
# ./src/main.ts
# multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
webpack: Failed to compile.
If i manually edit myLibrary.es5.js and remove /index everything works fine.
(All process is highly inspried by #angular/material buildind process)
All right, found my problem but for un unknown reason npm did install #angular/material with full code instead of builded version. I was having all .ts files and index.ts so I guess tsc did natuarlly used it.
Solved it we deleting node_modules folder and running npm i again.

Categories