create-react-app with typescript - how to put types in separate file - reactjs

I'm using CRA with typescript (create-react-app myapp --typescript)
I have some typescript stuff in my App.tsx that I would like to store externally, and I've tried creating App.d.ts, index.d.ts, module.d.ts and none of it works.
Here's the interface I'm using:
declare interface IArgs {
home: string,
away: string
}
What do I need to do to be able to declare all my Typescript stuff in a file that my source files can share?

Put in external file eg. interfaces/interfaces.ts:
export interface IArgs {
home: string,
away: string
}
Then in App.tsx where you want to use it you import it by: import { IArgs } from 'interfaces/interfaces'; and use it for your needs.

Related

How do I import jStat in a Svelte project

I have a Typescript file in a Svelte project and would like use jStat https://github.com/jstat/jstat like the following:
export namespace Statistics
{
export function cdfNormal (x:number, mean:number = 0, standard_deviation:number = 1)
{
return jStat.normal.cdf(x,mean,standard_deviation);
}
};
I installed it via npm install --save jstat
I tried
import _ from "jstat";
and
var { jStat } = require('jstat')
But both didn't work.
The package says:
Currently jStat is exposed as j$ and jStat inside an object, rather than exported directly. This may confuse some module loaders, however should be easily remedied with the correct configuration.
But just calling jStat doesn't work either. What am I doing wrong?
The package should be imported as:
import jStat from 'jstat';
All the functions (e.g. mean) will be on the this default export object. The import has to be in the file using it.
The package supplies no types and no third party types (#types/jstat) seem to exist. You can type the module manually to any degree you like. E.g. add a file jstat.d.ts like this:
declare module 'jstat' {
const jStat: {
mean: (arr: number[]) => number;
// ...
};
export default jStat;
}
Or just declare it any if you do not mind the lack of type safety.

How to use typescript typings without breaking code splitting feature?

I have a React-App initialized with 'create react-app my-app --template typescript' and i want to use code splitting for a big package. So i am using:
import('very-big-package').then(
coolStuff => {
...do some crazy stuff with 'coolStuff'
}
)
Now i want to pass the imported 'coolStuff' to another class constructor:
import('very-big-package').then(
coolStuff => {
return new OtherClass(coolStuff);
}
)
So how do i define the typings in the 'OtherClass' constructor without using a regular import like:
import coolStuff from 'very-big-package' //which will overrides the dynamic import
class OtherClass{
constructor(arg:typeof coolStuff){
...working with arg
}
}

How to correctly import custom types in typescript

I have custom type in src/#types/app.d.ts ( export type AuthKeyT = string )
I would like to use it in tsx react file (using import { AuthKeyT } from '#types/app'), but I am getting an error:
Cannot import type declaration files. Consider importing 'app' instead of '#types/app'
So, when I use import { AuthKeyT } from 'app' I am getting:
Cannot find module 'app'.
So.. what is wrong? How should I import custom type?
I am using typescript 3.7.2 in react app.
You're facing this error because #types/... is a global import. For example import { AuthKeyT } from '#types/app' means your're trying to import from #types that is in node_modules.
You can fix this by changing #types to something like #customTypes or by changing the path for your types folder something like #src/types... while importing.
As the error says, you can't import a .d.ts file in TypeScript.
import ... from 'app' mean implicitly import ... from 'app.ts' or this file don't exist so you get the second error.
If you want to use your types using this import, you have to write them in a simple .ts file like that:
src/#types/app.ts:
export type AuthKeyT = string
With this structure you will be able to import this type using:
import { AuthKeyT } from 'app'
You can also add path to your compilterOptons in the tsconfig.json like this:
"compilerOptions": {
"paths": {
"types/*": [
"./#types/*"
]
}
}
and then import { AuthKeyT } from 'types/app'

Is there a way to import an MDX or MD markdown file in React and use it in a data array?

I want to make a list of blog posts and therefor I thought it would be easy to use MDX because it helps with styling each blog text. But I don't know if it's possible to import a MDX file and put it in blogs.text.
I tried to use the npm package mdx.macro with it's function importMDX, but I get an error which says that the imported file is outside the src/.
mdx.macro documentation: https://www.npmjs.com/package/mdx.macro
import React, { lazy } from 'react';
import { importMDX } from 'mdx.macro';
const blog1 = lazy(() => importMDX('./blog1.md'));
export const blogs = [
{
title: "Hello World",
subtitle: "subtitle",
text: blog1
}
];
export default blogs;
I import this file in my blog and loop through all the items. But the importMDX keeps giving me the following error:
Module not found: You attempted to import
node_modules\.cache\mdx.macro\Content.6cbf05377c.mdx.js
which falls outside of the project src/ directory.
Relative imports outside of src/ are not supported.
Maybe there's an easier option than this?
Thanks in advance!
Adding to #mfakhrusy's answer , I had to change my blogs.js file to
import { mdx } from 'mdx.macro';
import Blog1 from './Blog1.js';
export const blogs = [
{
title: "My experiences as an intern working without getting paid",
subtitle: "And the difficulties that come along with being undervalued by a company",
text: <Blog1 />
}
];
export default blogs;
And my Blog1.js file contains this
import React from 'react';
import { mdx } from 'mdx.macro';
export const Blog1 = mdx`
# Don't Panic
Since we decided a few weeks ago to adopt the leaf as legal tender, we have, of course, all become immensely rich.
`
export default Blog1;
So now I can write blogs in markdown format and loop through them to show them on my website!
According to The create-react-app imports restriction outside of src directory
It's a restriction from CRA developer. You can try to eject your CRA app and try it again. (see eject script on package json), and remove ModuleScopePlugin from webpack config. Be careful though, eject is a one-way trip, you cannot go back.
It happens because from what I've seen from the doc, the package tries to generate a cache file which being imported later by the app, and CRA would prohibit that by throwing that error you encountered.

Create a typescript definition file for a 3rd party node module (react-signature-canvas)

I'll use React-Signature-Canvas as the example.
the react-signature-canvas node module install looks like this in my project dir:
react-signature-canvas
build
index.js
src
bezier.js
index.js
point.js
LICENSE
package.json
README.md
The index.js file looks has the following signature:
export default class SignatureCanvas extends Component {
This looks pretty straight forward. I figured I would just create an index.d.ts in the module's root dir, and get it working, then figure out a better place to store it in my project later (i.e., outside of node_modules, with is in gitignore).
But I can't seem to get it to work. My typings file looks like this:'
declare module 'react-signature-canvas'
{
interface ISignatureCanvasProps
{
velocityFilterWeight?: number;
minWidth?: number;
maxWidth?: number;
dotSize?: number;
penColor?: string;
backgroundColor?: string;
onEnd?: () => void;
onBegin?: () => void;
canvasProps?: any;
}
class SignatureCanvas extends React.Component<ISignatureCanvasProps, any>
{
}
export = SignatureCanvas;
}
I am I am trying to use the Signature Pad like this:
import * as React from 'react';
import SignatureCanvas = require('react-signature-canvas');
export class DeliverySignature extends React.Component<any, undefined>
{
public render(): JSX.Element
{
return (
<div>
<h4>Signature</h4>
<SignatureCanvas
canvasProps={{width: 500, height: 200}} />
</div>
);
}
}
Everything compiles fine, and Webpack seems happy. But when I go to load the page, I get
Uncaught (in promise) TypeError: Cannot read property 'replaceChild'
of null
at Function.replaceChildWithTree (DOMLazyTree.js:69)
at Object.dangerouslyReplaceNodeWithMarkup (Danger.js:41)
at Object.dangerouslyReplaceNodeWithMarkup [as replaceNodeWithMarkup] (DOMChildrenOperations.js:124)
at ReactCompositeComponentWrapper._replaceNodeWithMarkup (ReactCompositeComponent.js:784)
at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:774)
at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)
at Object.performUpdateIfNecessary (ReactReconciler.js:157)
at runBatchedUpdates (ReactUpdates.js:150)
What am I missing here? I am assuming I have imported incorrectly.
Thanks.
TypeScript has nothing to do with your error. The declaration file purpose is to help the compiler help you, but your code can run without them.
Nevertheless, your declaration file is incorrect. It's not supposed to contain any implementation. {} is also a kind of implementation. Consider this question in order to fix that. But again, this is not the source of your error.
Also, the naming convention is filename.d.ts, not .dt.ts
It seems like you are importing correctly. You can change it to:
import * as SignatureCanvas from 'react-signature-canvas';
But it's the same thing, except for the later one is ES6-compliant.
As you can see in this pull request, types for react-signature-canvas were added to DefinitelyTyped library.
You can add it to your project by executing following commands:
yarn add #types/react-signature-canvas
OR (using NPM)
npm i #types/react-signature-canvas.

Resources