So most examples I found on importing jspm packages to typescript assumed that I wanted to use Systemjs to load and interpret them in the browser. However, I would rather like to use tsc to build commonjs modules and only import the js code, since it seems to me to be the more general and error-resistent approach to me.
So my directory structure looks like this:
src/index.ts
jspm_packages/...
config.js
tsconfig.json
With tsconfig having the following content:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"noEmitOnError": true,
"noImplicitAny": false,
"rootDir": "src",
"outDir": "target/app",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": true
},
"exclude": [
"jspm_packages",
"node_modules",
"typings",
"target"
]
}
For testing purposes, I installed angular 2 with jspm install npm:angular2 and tried to import it in my index.ts via import { bootstrap } from 'angular2/platform/browser';
When running tsc, I get the error
src/index.ts(1,27): error TS2307: Cannot find module 'angular2/platform/browser'.
Now I wonder, can I make jspm-packages known to typescript? I feel like I tried it all, removing the jspm_packages from the tsconfig exclude list, switching to node module resolution or systemjs module generation. Maybe I just haven't found the right combination. Any hints on what to try next?
I am also struggling with this same issue and after some research, I learned that there no good solutions to allow this as of yet.
Workarounds:
A) You can duplicate your dependencies and install it with npm. tsc should not throw any errors since its resolving from npm.
B) Change your tsconfig.json and map angular to the jspm path. For example
"baseUrl": ".",
"paths": {
"angular2/*": [
"jspm_packages/npm/angular2#2.0.0-beta.7/*"
],
"rxjs/*": [
"jspm_packages/npm/rxjs#5.0.0-beta.2/*"
]
}
See https://github.com/frankwallis/plugin-typescript/tree/master/examples/angular2 for a full example.
Note that "baseUrl" and "paths" are not official properties and only on the beta version of typescript compiler.
The issue is currently being tracked here:
https://github.com/Microsoft/TypeScript/issues/6012
Related
I have a React-Typescript application and had recently configured i18next setup for multi-language support. I believe all of the setups have been done correctly by following the guidelines of the official documentation. However, when I run the app, it gives me a bunch of compilation errors, such as;
Property 'changeLanguage' does not exist on type 'typeof import("...some_path_info.../node_modules/i18next/index")'.
or
Module '"i18next"' has no exported member 'Module'
I tried a bunch of different tsconfig.json configurations, such as including the type definition file from the node_modules folder of i18next, and other things, but none of them solved the issue, here is the current version of my tsconfig.json file;
"include": ["src"],
"compilerOptions": {
"target": "ES2019",
"lib": ["esnext", "dom", "dom.iterable"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./src",
"baseUrl": "." /* Specify the base directory to resolve non-relative module names. */,
"paths": {
"libdefs/*": ["src/libdefs/*"]
},
"strict": false,
"noImplicitReturns": false,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": false,
"noUnusedParameters": false,
"moduleResolution": "node",
"jsx": "react",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"downlevelIteration": true,
"resolveJsonModule": true
}
}
After spending lots of time searching and testing, I found a way to make it work, and can lead me to the real solution, however, I still couldn't figure it out. The thing is, when I go to the node_modules folder of the i18next, the default file structure looks like this;
Within this package, when I tried to move the index.d.ts type definition file inside the dist folder and then build my project, everything started to work magically without any further configuration or change. However, obviously, it is not a permanent solution.
Finally, I need a permanent solution to this problem, and my last finding about manipulating the package folder of i18next can give some hints.
Here are the versions for related packages;
"i18next": "^22.0.6",
"react-i18next": "^12.0.0",
Thanks.
I think the package that you used is not using in React.js that is for Next.js. I suggest using React-intl package for supporting multi language in react applications.
React-intl documentation
and also have a look on this blog which done localization using react-intl React i18n: A step-by-step guide to React-intl
I have 2 projects with common functionality.
I need to develop my own npm module that will use common code snippets for this.
I made a separate project that will contain this shared code (eg util).
At the moment I have done the following:
we have 3 projects: project-a, project-b, front-components
I'm posting a "front-components" project in our company's npm.
Then I just include it in the rest of the projects as dependencies in the package.json
To develop this module locally, I do the following:
I copy the node_modules folder from the desired project to "front-components"
ln -s ../project-a/node_modules ./node_modules
Making an npm link from project-a
npm link ../front-components
Developing
But now I am facing difficulty in configuring tsconfig.json
For example, in "front-components" there is such code:
import { DATE_FORMAT } from 'constants/date';
And I get an error:
Module not found: Can't resolve 'constants/date' in '..../front-components/src/hooks'
I think that the problem is in tsconfig.json, but I can't figure out why it occurs.
Question 1: Can I use some other approach to avoid copying node_modules into "front-components"? (I need the files to be in .ts and .tsx format, not d.ts)
Question 2: How can I solve the problem with imports?
P.S.: Maybe you have some advice on how to develop this kind of bundles, I will be grateful
tsconfig.json
{
"compilerOptions": {
/* Basic Options */
"target": "es6", // Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'.
"module": "esnext", // Specify library files to be included in the compilation.
"lib": [
// Specify library files to be included in the compilation.
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true, // Allow javascript files to be compiled
"jsx": "react-jsx", // Generates corresponding '.d.ts' file.
"noEmit": true, // Do not emit outputs.
"isolatedModules": true, // Transpile each file as a separate module (similar to 'ts.transpileModule').
/* Strict Type-Checking Options */
"strict": true, // Enable all strict type-checking options.
/* Additional Checks */
"noFallthroughCasesInSwitch": true, // Report errors for fallthrough cases in switch statement.
"noUncheckedIndexedAccess": true, // Include 'undefined' in index signature results.
/* Module Resolution Options */
"moduleResolution": "node", // Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).
"baseUrl": "src", // Base directory to resolve non-absolute module names.
"allowSyntheticDefaultImports": true, // Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
"esModuleInterop": true, // Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'.
/* Advanced Options */
"skipLibCheck": true, // Skip type checking of declaration files.
"forceConsistentCasingInFileNames": true, // Disallow inconsistently-cased references to the same file.
"resolveJsonModule": true
},
"include": ["src", "./global.d.ts"],
"files": ["node_modules/front-components/src/index.ts"],
"exclude": ["node_modules"]
}
As both your projects depends on same UI components it sounds like what you need is monorepo. It gives you a flexibility in dependency management in a way you need (current approach seems to be overcomplicated and not so efficient). Depending on package manager you use you can choose the approach for it. Here's a yarn workspaces based example. I do not mean you have to switch to yarn berry, it's just one very minimalistic example that gives you a breath idea of monorepo. My personal preference is Nx, so google for more info and good luck, enjoy coding!
I import the style file in my project like this:
import styles from '#src/styles.scss';
The tsconfig.json file contains:
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES5",
"jsx": "react",
"baseUrl": "./",
"paths": {
"#src/*": ["src/*"]
}
},
"include": ["src"],
"exclude": ["node_modules"],
"compileOnSave": false
}
But my Visual Studio Code is throwing error Cannot find module "#src/styles.scss". Although the assembly of the project occurs without errors. The styles.scss file does exist and is located in the src folder.
In the project I use webpack 5 and I have already specified aliases in its config.
Can you please tell me how to solve this visual problem?
Following our chat, I think that the reason IntelliSense is not working is that typescript paths look for .js(x)/.ts(x) extensions (which is not the case of .scss). The reason it works at build time is that webpack is taking care of it.
I recommend using a solution like module-alias to get rid of this warning on VSCode.
After a few days of searching for a solution, I still found it! The whole problem is that typescript only accepts files with .js(x)/.ts(x) extensions as modules.
Therefore, we need to manually specify that files with the .scss extension are also modules.
Create a typings folder in the root of the project. In this folder, create a declarations.d.ts file with the contents:
declare module '*.scss' {
const content: Record<string, string>;
export default content;
}
Now in the tsconfig.json file, add the typings folder:
{
...
"include": ["typings", "src"],
}
I hope my answer saves someone time!
I'm using Cypress in TypeScript, in WebStorm. I'd been working on project A1 for a few weeks, I added Cypress, I add TS to Cypress, and then things started getting a little funny, including js files being added alongside the ts files, both in Cypress and in my src folder. (tsx files didn't do this, only ts)
So I restarted the project: I created a whole new Create React App project, A2, and started dragging the files one by one (or folder by folder) from A1 to A2. I added the Cypress files to A2 by running cypress open when A2 had no cypress files in it, which caused Cypress to add its files. Then I added my tests from A1 (copying code into new files, not copying the files) and set up various config files and stuff such that:
TS recognizes my custom cypress commands
No extra JS files are created
Then I deleted all the files in the A1 project and dragged in all the files, minus the node_modules folder, from A2, and ran yarn install.
Everything works, except the Cypress folder still creates js files alongside the ts files.
It's very hard to pinpoint the actual moment when this happens: I had written this post and abandoned it because things seemed to be working fine. But then a few hours later I noticed the js files were back! Only in the Cypress folders, including ALL ts files in the Cypress folders (/integration, /plugins, etc).
Here's some tsconfigs:
cypress/tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["es5", "dom"],
"types": ["cypress"]
},
"include": [
"**/*.ts", "**/*.d.ts"
]
}
<project_root>/tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
Oh no, and now all of a sudden it's making js files out of ts in my src folder!
When I delete all these extra js files (which, in the src folder, generate warnings in the running app), I also get these kind of warnings from WebStorm:
Oops! Something went wrong! :( ESLint: 6.7.2. ESLint couldn't find the plugin "eslint-plugin-import". (The package "eslint-plugin-import" was not found when loaded as a Node module from the directory "/Users/tuzmacbookpro2017/dev/Sunrise/IVD".) It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: npm install eslint-plugin-import#latest --save-dev The plugin "eslint-plugin-import" was referenced from the config file in "nginx/front_end/package.json ยป eslint-config-react-app". If you still can't figure out the problem, please stop by https://gitter.im/eslint/eslint to chat with the team.
The react server and the cypress server and runner all seem happy though.
Help! What's with these js files? (I know TS transpiles ts into js or whatever, but usually the files don't actually show up like this)
Please make sure that Recompile on changes is not enabled in Settings | Languages & Frameworks | TypeScript
You can pass to the configuration file
false value to the next fields:
fixturesFolder
integrationFolder
pluginsFile
etc...
(Or just for the fields you need of course.)
documentation:
https://docs.cypress.io/guides/references/configuration.html#Folders-Files
I have a tsconfig.json file with the following:
{"compilerOptions": {
"module": "commonjs",
"noImplicitAny": false,
"removeComments": true,
"preserveConstEnums": true,
"outDir": "./target/src/",
"rootDir": "./src/main/webapp/",
"sourceMap": true,
"experimentalDecorators": true
},
"exclude": ["node_modules", "target"]
}
When I run tsc I get the error:
error TS6059: File '../node_modules/ng2-select/components/ng2-select-config.ts' is not under 'rootDir' 'main/webapp'. 'rootDir' is expected to contain all source files.
The culprit seems to be when I try to load ng2-select in a file:
import {Component} from 'angular2/core';
import {select} from 'ng2-select';
If I run tsc without the second import it's fine. If I add the second I get that error.
Any ideas as to why it's trying to compile ng2-select even though it's supposed to be ignored?
Thanks!
This is either an issue with the structure of the ng2-select module or a bug with the typescript compiler.
The issue is caused by having .ts and .d.ts files in the same directory as each other within the module directory that you are trying to load from. This seems to cause the typescript compiler to recompile the module then getting confused because it compiled something outside of the rootDir.
I have had the same issue and have raised it on the module's GitHub repository. This answer may help you for now though it isn't ideal. Hopefully there'll be a fix soon.
Update
The latest release fixes this issue.