Sorry everyone, I've been struggling trying to understand why I need the
/// <reference path="../typings/browser.d.ts" />
module App {
angular.module("app", [""]);
}
I'm using typings and here is my tsconfig:
{
"compilerOptions": {
"experimentalDecorators": true,
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": false,
"sourceMap": true,
"target": "es5",
"module": "commonjs"
},
"files": [
],
"exclude": [
"node_modules",
"wwwroot"
]
}
I found already several posts about, but every time a different answer and a different scenario.
I use Visual Studio 2015 with ReSharper, TypeScript 1.8.5
Once I remove <reference... tag ReSharper says "Cannot find name 'angular'" but the application runs normally. (probably because it cannot find the intellisense anymore)
Has anyone faced the same problem? Am I missing something?
From the docs on tsconfig:
If no "files" property is present in a tsconfig.json, the compiler
defaults to including all TypeScript (*.ts or *.tsx) files in the
containing directory and subdirectories. When a "files" property is
present, only the specified files are included.
You are using an empty files array ("files": []) which means no files are going to be included in the compiler context. Either add all your references to the files array, or remove the files property completely to allow the compiler to include all TS files in context.
Alternatively, you can use import and export module syntax instead.
I use one _reference.ts file with all referenced *.d.ts lybraries which I use. The typescript compiler use it information for import defenitions about js lybraries. The second case there reference are used is managing the order of ts files include into resulting js file. Another words if you add reference in file B.ts to A.ts in resulting js will be contains A.js first and B after. It's not often needed because TSC is smart and ordered file by types using but some times It's usefull then you use some suff from A.ts in B.ts dynamicly (not stronrly typed).
Related
I'm attempting to use TypeScript's paths option in my tsconfig.json file. I've used paths before in my other web applications using React. Yet, for some reason, Native refuses to work with it.
This is my tsconfig.json file:
// Added by default by React Native
"extends": "#tsconfig/react-native/tsconfig.json",
// My options
"compilerOptions": {
"baseUrl": "./App",
"paths": {
"#Assets/*": ["Assets/*"],
"#Image/*": ["Assets/Images/*"],
},
"skipLibCheck": true,
}
This is my folder structure:
project
|__App
| |__Main.tsx
| |__Assets
| |__Images
| |__Test.png
|__tsconfig.json
And inside my Main.tsx file, this is how I'm attempting to use it:
const test = require("#Image/Test.png");
But, this results in the error:
Unable to resolve module #Image/Test.png from project/App/Main.tsx: #Image/Test.png could not be found within the project or in these directories.
I've attempted all of the answers within this thread with no different outcome.
I know that the file does exist because it works perfectly fine when I change the require path to the absolute path.
I have a Project (Existing Project) for which frontend is writen in namespaced typescript.
I cannot rewrite all typescript file from namespaced approach to export/import es6 syntax.
However the below code is working fine. and no issue if i add my new ts module or react component as far i wrap it in namespace and call it by Class or with namespace prefix if its in other namespace.
Issue is i cannot use external modules with import statement.How can i use..?since import statement is throwing error.
To be more specific for below code i wanted to use react-redux,
When i check the node_moduels folder i saw #types folder from where the React namesapce is referred
I Assume Due to this line in tsconfig
"typeRoots": [
"./node_modules/#types/"
]
But when i install npm install --save #types/react-redux it also created react-redux folder with index.ts under #types folder in node modules. but it doesnt have the Namespace export lines how the React type file has some thing like below.
export as namespace React;
declare namespace React {
....
}
Ultimately..How can i use third party node moudles, especially react-redux in this project.
Or any simple node module and access it in any ts file simple moudles such as "react-bootstrap"
Below is the simple ts file for react componnet wrapped in namesapce whihc is working fine (except import staement)
import { createStore } from 'redux'; //if i add this line this is throwing error.
namespace Profile.Sample {
import { createStore } from 'redux'; //this too throwing error, without these lines my code is working fine.
export class Profiles extends React.Component<any> {
constructor(props) {
super(props);
this.state = { brand: "Ford" };
}
render(): React.ReactNode {
return (
<sect
<div className="container-fluid">
<div className="row">
<div className="col-lg-12">
<div className="main-title">
<h2>Profiles</h2>
<p>Lorem ipsum dolor sit amet, consectetur adi</p>
</div>
</div>
</div>
</div>
</section>
);
}
}
}
Below is my tsconfig
{
"compileOnSave": true,
"compilerOptions": {
"preserveConstEnums": true,
"experimentalDecorators": true,
"declaration": true,
"emitBOM": true,
"jsx": "react",
"noEmitHelpers": true,
"inlineSourceMap": true,
"inlineSources": true,
"outFile": "wwwroot/Scripts/site/Profiles.js",
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"target": "es5",
"typeRoots": [
"./node_modules/#types/"
]
}
}
I know namespace is not the recommended approach going forward..but this is an existing project and cannot rewrite all files from namespace to import/export statements.
Ok, let's make it runnable step by step:
Although you did not state it explicitly, I assume you get the error message Cannot compile modules using option 'outFile' unless the '--module' flag is 'amd' or 'system'.. The option outFile generates one master file with all your code concatenated in it. Since you are using "target": "es5" in your tsconfig.json, the default value for module is commonjs. commonjs is the module syntax widely used for node.js (var x = require('x') / exports.x = x) and this syntax does not support merging code into one file, therefore it is prohibited. But you want to use your code in the browser, so commonjs is not supported there anyways. So the first thing to do is
Insert "module": "AMD" into your tsconfig.json file.
AMD is a module syntax usable in the browser. You can also use "UMD", which is just an extension, so that the module supports AMD and commonjs modules.
To avoid some more configuration later on, you should also
Change "outFile": "wwwroot/Scripts/site/Profiles.js" to "outDir": "wwwroot/Scripts/site" in your tsconfig.json file.
Setting module to AMD changes the default of moduleResolution from node to classic, but that's not good, because then import {createStore} from 'redux' will fail with the error message Cannot find module 'redux'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?. Therefore
Include "moduleResolution": "node" into your tsconfig.json file.
In your code you define a class which extends another base class. If you transpile this inheritance, a special function __extends is required. With the current setup this function is not generated by typescript and you get the error Uncaught ReferenceError: __extends is not defined. Therefore
Remove "noEmitHelpers": true.
Now all your files can be transpiled to AMD modules. But to use those modules, you need a module loader. The most popular one is require.js. To use it,
Insert <script data-main="setup" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script> into your HTML file.
You can also download it and serve it yourself. data-main="setup" means that after require.js has been loaded, the script setup.js is executed. This script is created in the next step.
require.js needs some configuration to find all the modules. So
Create wwwroot\Scripts\site\setup.js:
requirejs.config({
appDir: ".",
paths: {
'react': ['./node_modules/react/umd/react.production.min.js', 'https://unpkg.com/react#16/umd/react.production.min'],
'react-dom': ['./node_modules/react-dom/umd/react-dom.production.min.js', 'https://unpkg.com/react-dom#16/umd/react-dom.production.min'],
'redux': ['./node_modules/redux/dist/redux.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min'],
},
});
requirejs(['entryPoint'], function() {
console.log("Entry point 'index' has been loaded!");
return {};
});
In the first part require.js is configured. Especially, the locations of external modules (modules installed via npm) are defined. Here the locations of react, react-dom and redux are set to the locations in the node_modules folder with external files from content delivery networks (CDN) as backups. You can also remove one of the locations. They are requested from left to right and moving on if one request fails. If you use the locations in your node_modules folder, you must serve them from your webserver as well!
In the second part the module entryPoint is executed. This is the entry point to your app. Change the name to whatever you want to be your entry point. If you want the module defined in the file someOtherFile.js to be the entry point, then write requirejs(['someOtherFile'], ....
To transpile all files run
tsc --project tsconfig.json.
Serve all files in the directory wwwroot/Scripts/site including your HTML file. For testing purposes you can use
npx serve.
You can see the slightly modified code here: https://codesandbox.io/s/elated-fermat-ie2ms?file=/src/index.tsx.
I am using TypeScript with React, and TypeScript is still checking libraries in node_modules folder, although I have "skipLibCheck" set to true in tsconfig.json..
Here's my tsconfig.json (I added the exclude section for troubleshooting, which also didn't work):
{
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "commonjs",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"typeRoots": [
"./node_modules/#types"
],
"types": [
"es6-promise",
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection"
]
},
"exclude": [
"node_modules",
"./node_modules",
"./node_modules/*",
"./node_modules/#types/node/index.d.ts",
]
}
React version am using is 15.4.2, and TypeScript is installed globally... I had version 3.7.2, and I upgraded it to 3.7.3 because I read somewhere that skipLibCheck doesn't work with 3.7.2 ..
The error I am getting when trying to build the project with gulp is:
Error - typescript - node_modules\gsap\types\gsap-utils.d.ts(97,75): error TS1144: '{' or ';' expected
If I set skipLibCheck to false, and build the project, I'll have MANY more errors. So seems like the skipLibcheck works partially.
Any idea how to solve this? I am still new to TypeScript. Any help would be appreciated.
skipLibCheck is not meant to prevent all type checking in node_modules. Although it may work for some projects, but it's just a coincidence. You could say it works partially, true. Here's what it does:
Skip Lib Check - skipLibCheck
Skip type checking of declaration files.
This can save time during compilation at the expense of type-system
accuracy. For example, two libraries could define two copies of the
same type in an inconsistent way. Rather than doing a full check of
all d.ts files, TypeScript will type check the code you specifically
refer to in your app’s source code.
A common case where you might think to use skipLibCheck is when there
are two copies of a library’s types in your node_modules. In these
cases, you should consider using a feature like yarn’s resolutions to
ensure there is only one copy of that dependency in your tree or
investigate how to ensure there is only one copy by understanding the
dependency resolution to fix the issue without additional tooling.
skipLibCheck was introduced in Typescipt 2.0, so upgrading Typescript isn't really a fix. Yet again it may work for some people.
Now I had a case when I had to add a library using Typescript 4 to a project using Typescript 3. It was raining errors on build. Having the same version of typescript helped. The version of typescript would be specific to your project here.
The only quick solution I know is to use require instead of import (my project was backend):
import * as lib from 'lib';
const lib = require('lib');
skipLib can only skip .d.ts errors. But if you use .ts files directly from node_modules, tsc can not igonre the type errors. You may try add "// #ts-noCheck" before every .ts file in node_modules.
Here's my node script for adding // #ts-ignore before every .ts、*tsx file in node_modules. You can run it before run tsc.
// 将 node_modules 下面的每个 ts,tsx 文件头部都加上 // #ts-noCheck,以忽略 node_modules 下面的类型错误
const fs = require('fs');
const path = require('path');
const traversalPath = `./node_modules`;
function folderTraveral(filePath) {
// 根据文件路径读取文件,返回文件列表
fs.readdir(filePath, function (err, files) {
if (err) {
console.warn(err);
} else {
// 遍历读取到的文件列表
files.forEach(function (filename) {
// 获取当前文件的绝对路径
const filedir = path.join(filePath, filename);
// 根据文件路径获取文件信息,返回一个fs.Stats对象
fs.stat(filedir, function (eror, stats) {
if (eror) {
console.warn('获取文件stats失败');
} else {
const isFile = stats.isFile(); // 是文件
const isDir = stats.isDirectory(); // 是文件夹
if (
isFile &&
!filedir.endsWith('d.ts') &&
(filedir.endsWith('ts') || filedir.endsWith('tsx'))
) {
let content = fs.readFileSync(filedir, 'utf-8');
if (!content.startsWith('// #ts-nocheck')) {
content = '// #ts-nocheck \n' + content;
fs.writeFileSync(filedir, content, 'utf-8');
}
}
if (isDir) {
folderTraveral(filedir); // 递归,如果是文件夹,就继续遍历该文件夹下面的文件
}
}
});
});
}
});
}
folderTraveral(traversalPath);
Consider the following settings in jsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"#components/*": ["src/components/*"],
"#constants/*": ["src/constants/*"]
}
}
}
When I attempt to import app-constants.js file in my components through:
import AppConstants from "#constants/app-constants";
I seem to get the following error:
Module not found: Can't resolve '#constants/app-constants'
My app-constants.js file is located directly in the src/constants folder:
Any idea why this is happening?
EDIT
I Tried using this:
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
And works when calling directly onto the folders like constants/app-constants.js
But doesn't when I try the first method.
It would be great if someone is able to enlighten me of my mistakes.
Your code looks good and you can verify it by intellisense e.g:
import AppConstants from "#constants/";
it will show app-constants in intellisense.
Now the problem is that react is not supporting aliases yet, but will support very soon.
I don't know if we will add support for aliases anytime soon. I
personally don't have time to work on it right now. I think the
current options with setting the baseUrl to . or src is sufficient for
tackling the struggles with relative imports. Beyond that it's just
personal preference like using # instead of src as prefix.
https://github.com/facebook/create-react-app/issues/7795
I am compiling all TypeScript in my angular project but I am getting the well known error:
error TS2300: Duplicate identifier 'require'.
However most people who have this issue are running into it because they have two files that cause the duplication error. In my case it is because of the word 'require' being used twice in the same file.
/typings/globals/angular/index.d.ts(1707,9):
and
/typings/globals/angular/index.d.ts(1717,9):
it is the default angular typings definition file being pulled from the dt source.
I have TypeScript both locally and globally. I tried removing the local copy but that errors out. Here is my tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"files": [
"typings/index.d.ts"
]
}
and my typings.json:
{
"globalDependencies": {
"angular": "registry:dt/angular#1.5.0+20160627014139",
"bootstrap": "registry:dt/bootstrap#3.3.5+20160619023404",
"jquery": "registry:dt/jquery#1.10.0+20160620094458"
}
}
and lastly my main index.d.ts:
/// <reference path="globals/angular/index.d.ts" />
/// <reference path="globals/bootstrap/index.d.ts" />
/// <reference path="globals/jquery/index.d.ts" />
You shouldn't list d.ts files in the files section of your tsconfig.json file. That is the place that you list the files that you have written that need to be transpiled into javascript. The problem you're seeing is caused by the transpiler trying to convert your typings/index.d.ts file into javascript, which it should not do. The typings definitions are really only there so that your code editor can provide type hinting, warn you about errors, and do code completion.
Take a look at this overview of the tsconfig.json file.