I am working on nodejs application in typescript with angular which is also in typescript. i have use gulp to transpile the files to js. but when i run command to transile my angular file it gives me error TS2300: Duplicate identifier
here is my gulp.config.js
module.exports = function () {
var config = {
allTs:'./src/**/*.ts',
typeings:'./typings/**/*.ts',
server:'./server.ts',
tsOutPutPath:'./app',
allNgTs:'./client/**/*.ts',
ngOut:'./public/scripts/src'
};
return config;
}
here is my gulp task
gulp.task('compile-ng', function () {
var sourceTsFiles = [
config.typeings,
config.allNgTs
]
del(['public/scripts/**/*.js','public/scripts/**/*.html']).then(paths => {
console.log('Deleted files and folders:\n', paths.join('\n'));
});
var tsResult = gulp
.src(sourceTsFiles)
.pipe(sourcemaps.init())
.pipe(tsc(tsProject));
return tsResult.js
.pipe(sourcemaps.write('../map'))
.pipe(gulp.dest(config.ngOut));
});
Your tsconfig.json file should exclude node_modules and any d.ts files that may conflict with angular d.ts i.e:
{
"compilerOptions": {
"target": "ES5",
"module": "system",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": false
},
"exclude":[
"fonts",
"images",
"img",
"libs",
"navigation",
"node_modules",
"pagehtmls",
"typings"
]
}
Add ngTypeings:'./node_modules/angular2/typings/**/*.ts', to gulp.config.json file and use this angular2 typing in task instead of typeings
var sourceTsFiles = [
config.ngTypeings,
config.allNgTs
]
Related
I have created a npm package using typescript react and rollup.js. I have link it to the project using yalc (similar to npm link) and getting the following error:
Server Error
Error: Cannot find module './tslib.es6-eaa548e7.js'
Require stack:
- /Users/paul/Projects/test-project/.next/server/pages/index.js
Package structure:
- dist/
- ContactForm7.d.ts
- ContactForm7.js
- index.d.ts
- tslib.es6-eaa548e7.js
- Wordpress.d.ts
- Wordpress.js
- src/
- package.json
- rollups.config.js
- tsconfig.json
pages/index.tsx is importing the package with:
import { getPage } from 'package-wordpress/dist/Wordpress';
This is the starting contents of dist/Wordpress.js which looks to be initiating the error:
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var tslib_es6 = require('./tslib.es6-eaa548e7.js'); // this is where error occurs
var axios = require('axios');
var cacheData = require('memory-cache');
rollup.config.js:
import typescript from '#rollup/plugin-typescript';
import replace from 'rollup-plugin-replace';
import commonjs from '#rollup/plugin-commonjs';
export default {
input: {
Wordpress: 'src/Wordpress.tsx',
ContactForm7: 'src/ContactForm7.tsx'
},
output: {
dir: 'dist',
format: 'cjs',
exports: 'named',
},
plugins: [
typescript({
tsconfig: 'tsconfig.json'
}),
replace({
'process.env.MY_VARIABLE': JSON.stringify(process.env.MY_VARIABLE)
}),
commonjs()
],
external: ['react'],
};
tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"jsx": "react",
"module": "esnext",
"lib": ["esnext"],
"strict": true,
"esModuleInterop": true,
"declaration": true,
"outDir": "dist",
"importHelpers": true
},
"include": [
"src",
"src/index.tsx"
]
}
I am setting up a new project with Remix (remix.run) and I am trying to configure Cypress/ESLint for component testing. I have a TestComponent.cy.ts with some boilerplate code:
describe('TestComponent.cy.ts', () => {
it('playground', () => {
// cy.mount()
})
})
However, the describe function throws this Error:
Parsing error: ESLint was configured to run on `<tsconfigRootDir>/component/TestComponent.cy.ts` using `parserOptions.project`: <tsconfigRootDir>/../../../../../../users/tduke/desktop/dev/blog/cypress/tsconfig.json
However, that TSConfig does not include this file. Either:
- Change ESLint's list of included files to not include this file
- Change that TSConfig to include this file
- Create a new TSConfig that includes this file and include it in your parserOptions.project
I have tried to reconfigure my .tsconfig.json and .eslintrc.js to no avail. Currently, this is what those files look like:
tsconfig.json:
{
"exclude": ["./cypress", "./cypress.config.ts"],
"include": ["remix.env.d.ts", "**/*.ts", "**/*.tsx", "./cypress/component/*.cy.ts", "./cypress/**/*.cy.ts",
],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2019"],
"types": ["vitest/globals"],
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"module": "CommonJS",
"moduleResolution": "node",
"resolveJsonModule": true,
"target": "ES2019",
"strict": true,
"allowJs": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"~/*": ["./app/*"]
},
"skipLibCheck": true,
// Remix takes care of building everything in `remix build`.
"noEmit": true
}
}
.eslintrc.js:
/** #type {import('#types/eslint').Linter.BaseConfig} */
module.exports = {
extends: [
"#remix-run/eslint-config",
"#remix-run/eslint-config/node",
"#remix-run/eslint-config/jest-testing-library",
"prettier",
],
env: {
"cypress/globals": true,
},
parserOptions: {
project: './tsconfig.json'
},
plugins: ["cypress"],
// We're using vitest which has a very similar API to jest
// (so the linting plugins work nicely), but we have to
// set the jest version explicitly.
settings: {
jest: {
version: 28,
},
},
};
I also encountered the same problem, I solved the problem by removing the project property under parserOptions
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
// project: 'tsconfig.json',
tsconfigRootDir: __dirname,
},
You should add ["./.eslintrc.js"] to your tsconfig.json file:
{
"include": ["./.eslintrc.js"],
//...
}
This is what I ended up putting in my .eslintrc.json:
module.exports = {
...
parserOptions: {
parser: '#typescript-eslint/parser',
project: './tsconfig.json',
tsconfigRootDir: __dirname,
},
};
It may have been that the project needed to be ./tsconfig.json instead of tsconfig.json. My tsconfig file is in the project root.
And this brought up some more errors linting things like babel config so I created an .eslintignore file and added those in there:
.eslintrc.js
ios/
android/
*.config.js
This solved all my issues.
I export const FontXLarge = 18; in ThemeFont.ts.
When I want to use it, I used to use import {FontXLarge} from '../theme/ThemeFont';
After I add
{
"name": "theme"
}
I can use import {FontXLarge} from 'theme/ThemeFont'; but I can't link to the folder.
So I think that if I declare module 'ThemeFont' I can link it. And the fact that I did it. When I ctrl + click (or alt + click in VSCode, depending on your setting), it can open the file ThemeFont.ts when I use import {FontXLarge} from 'ThemeFont';
declare module 'ThemeFont' {
export const FontXLarge = 18;
}
When hover, it will show like that
But it shows error when build: Unable to resolve module ThemeFont in node_modules
We can use this library to declare local component https://github.com/tleunen/babel-plugin-module-resolver
My config for it:
create/edit: tsconfig.json
{
"compilerOptions": {
"skipLibCheck": true,
"allowJs": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"isolatedModules": true,
"jsx": "react",
"lib": ["es6"],
"moduleResolution": "node",
"noEmit": true,
"strict": true,
"target": "esnext",
"baseUrl": "./app",
"paths": {
"#/*": ["./*"]
},
"outDir": "../dst/",
"typeRoots": ["node_modules/#types"]
},
"lib": ["es2016"],
"exclude": [
"node_modules",
"babel.config.js",
"metro.config.js",
"jest.config.js"
]
}
create/edit jsconfig.json
{
"compilerOptions": {
"paths": {
"#/*": [
"./app/*"
]
}
}
}
create/edit jsconfig.js
System.config({
paths: {
'#/*': './app/*',
},
})
edit babel.config.js
const presets = ['module:metro-react-native-babel-preset'];
const plugins = [
[
'react-native-reanimated/plugin',
// {
// globals: ['__scanQRCodes', '__decode'],
// },
],
[
'module-resolver',
{
root: ['./app'],
extensions: ['.js', '.json'],
alias: {
'#': './app',
},
},
],
];
const env = {
production: {
plugins: ['react-native-paper/babel'],
},
};
module.exports = {
presets,
plugins,
env,
};
Now you can use
import {FontXLarge} from '#/Theme/ThemeFont';
remember that after config it, resetting app cache:
yarn start --reset-cache
Here is my test in a file called Carousel.Snapshots.test.tsx
describe('Carousel Snapshot', () => {
it('renders as expected', () => {
const props = getPropsForSnapshot();
const tree = renderer.create(<Carousel {...props} />);
console.debug(tree);
expect(tree).toMatchSnapshot();
});
});
When I run jest with
jest -c ./config/jest.config.js --detectOpenHandles --forceExit --watch
Jest returns this error:
FAIL .../carousel/Carousel.Snapshots.test.tsx
● Test suite failed to run
Could not find source file: '...\carousel\Carousel.Snapshots.test.ts'.
at getValidSourceFile (node_modules/typescript/lib/typescript.js:157093:29)
at Object.getSemanticDiagnostics (node_modules/typescript/lib/typescript.js:157351:36)
at TsCompiler._doTypeChecking (node_modules/ts-jest/dist/compiler/ts-compiler.js:302:119)
at TsCompiler.getCompiledOutput (node_modules/ts-jest/dist/compiler/ts-compiler.js:133:18)
at TsJestCompiler.getCompiledOutput (node_modules/ts-jest/dist/compiler/ts-jest-compiler.js:13:39)
at TsJestTransformer.process (node_modules/ts-jest/dist/ts-jest-transformer.js:182:37)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.421 s
Ran all test suites related to changed files.
Watch Usage: Press w to show more.
It seems to be looking for a version of the file with a .ts extension, but the file has a .tsx extension.Here's my jest config
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
rootDir: '../',
testPathIgnorePatterns: [
'<rootDir>/dist/',
'<rootDir>/node_modules/',
'<rootDir>/src/server',
],
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/config/jest-tools/fileMock.js",
"\\.(css|less)$": "<rootDir>/config/jest-tools/styleMock.js"
},
setupFiles: [
"<rootDir>/config/jest-tools/testSetup.js"
],
};
I was expecting the snapshot test to be successful
The solution was with the tsconfig.json file.
Adding
esModuleInterop: true
to the compilerOptions solved my problem.
{
"compilerOptions": {
"outDir": "./build/", // path to output directory
"sourceMap": true, // allow sourcemap support
"strictNullChecks": true, // enable strict null checks as a best practice
"module": "esnext", // specifiy module code generation
"jsx": "react", // use typescript to transpile jsx to js
"target": "es5", // specify ECMAScript target version
"strict": true /* Enable all strict type-checking options. */,
"allowJs": true, // allow a partial TypeScript and JavaScript codebase
"allowSyntheticDefaultImports": true,
"noImplicitAny": true, // disallow implicit any type
"moduleResolution": "node",
"resolveJsonModule": true,
"lib": ["esnext", "es2019", "es2017", "es7", "es6", "dom", "dom.iterable"],
"baseUrl": ".",
"paths": {
"~/*": [ "./src/app/*" ],
"-/*": [ "./*" ]
},
"esModuleInterop": true
},
"include": ["./src"],
"exclude": [
".storybook",
"config",
"public",
"webpack",
"storybook-static",
"./node_modules/**/*"
]
}
Once that was added the jest tests ran as expected
I want to exclude imported libraries from my result bundle.
Lets say we have next code:
import * as angular from 'angular';
const app = angular.module('app',[]);
And we have this build task.
function buildTs(compileOptions) {
browserify(compileOptions)
.plugin(tsify, tsconfig.compileOptions)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest(path.dest.js));
}
When build will be finished, Angular lib will be included into bundle.js.
Can I avoid this?
My tsConfig:
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"noImplicitAny": false,
"removeComments": true,
"sourceMap": true,
"types": [
"angular",
"angular-cookies",
"angular-ui-bootstrap",
"angular-ui-router",
"jasmine",
"angular-mocks"
]
},
"include": [
"app"
],
"exclude": [
"node_modules"
]
}
Removing types from types not helps :)
This will make browserify ignore angularjs , and then it can be added from index.html .
var browserify = require("browserify")
browserify()
.ignore('angular')
Any option to include several files without adding .ignore(name) each time? With array or smth like this?
var tsProject = ts.createProject('tsconfig.json');
gulp.task('scripts', function() {
var tsResult = gulp.src("lib/**/*.ts")
// or
tsProject.src()
.pipe(tsProject());
return tsResult.js.pipe(gulp.dest('release'));
});
Thus , this might be a cleaner way to build Typescript files. In src , you can provide your own list of regular expression src files .