How to use path mapping with Jest? - reactjs

I'm moving forward with the project and I want to start writing tests.
But I came across a problem that I don't know how to solve.
I'm using path mapping in the project, but when I write the tests the page (or component) is not found.
I care like this
import Dashboard from '#pages/dashboard';
and the error is
Cannot find module '#pages/dashboard' from 'src/__tests__/pages/dashboard.test.tsx'
Does anyone know why?

After taking another look at the Jest documentation I realized that the jest.config.ts settings were wrong.
I changed it to this and it worked.
moduleNameMapper: { '^#pages/(.*)$': '<rootDir>/src/pages/$1' }
Just for the record, my tsconfig looks like this:
"paths": { "#pages/*": ["./src/pages/*"] }

Related

How do I get VS Code to understand my aliases in react native for command click?

So I'm using a package.json file to create custom aliases in my project
{
"name": "#name"
}
so that I can change this
import Component from '../../../some/deeply/ambiguous/name';
to this
import `Componentfrom '#name';
However, I can't command + click to jump to that module from the import statement, VS code cannot resolve the path.
There are a couple other ways to do this (https://www.novis.co/post/custom-aliases-in-react-native-with-babel/), is there is any way that I can do aliasing and somehow have visual studio code recognize the path and be able to jump to it?
Mine work and I've just added in the paths to tsconfig, maybe give that a go. Try adding in the paths into tsconfig.json in your root. Close and reopen VSCode.
baseUrl": ".",
"paths" : {
"#app/*" : ["src/*"]
}

Why do I have to use "require" instead of "import from" for an image in React?

I see that this answer suggests the syntax for importing images as shown below (commented out). In my case, it didn't work out (complaining there's no modules to find in that file) and I had to switch to the syntax that's currently active.
// import Author from "../assets/author.png";
var Author = require("../assets/author.png");
The difference I can imagine is that I'm using TypeScript (transpiling my TSX by awesome-typescript-loader and loading my PNG file-loader) and they seem to use JSX. But as far my understanding goes, it all transpiles to plain JS and require in the end.
Being a noob on React, I'm not sure what the reason of this discrepancy is but also I'm not sure what to google for to investigate myself.
This is more of a problem with typescript than webpack itself, you might need to declare modules on a declaration file.
Create a declarations.d.ts
Update your tsconfig.json
"include": [
"./declarations.d.ts",
],
Put this on that file:
declare module '*.png';
Error might be gone.
You can declare a module for your images like this:
declare module "*.png" {
const value: any;
export default value;
}
Then, you will be able to import your image like this:
import AuthorSrc from "../assets/author.png";
This is happening because webpack doesn't support image import out of the box. So you need to add a rule for that in the webpack config file. When you add a new rule, TypeScript doesn't automatically know that, so you need to declare a new module to resolve this. Without the module, you will be able to import images, but TypeScript will throw an error because you didn't tell to it is possible.
This issue has nothing to do with webpack or any bundler and is not quite a problem with typescript.
Typescript has stated that `require("path") is a way to include modules to the scope of your current module, whilst it can be also used to read some random files (such as json files, for example).
As Vincent and Playma256 specified, you can declare a module wildcard to match certain file types, so you can import it as an import statement. But you don't really need to do this. Typescript won't give you an error if you are trying to import a png or a json file (tslint might, but that depends on your configuration).
By the way, if your declaration is within the source folder of your project as defined in tsconfig.json, you don't need to include it as specified by Playma256.
I've created a sample project in node for you to test:
https://github.com/rodrigoelp/typescript-declare-files
I think you can solve this problem with Webpack&&typescript.The official webpage of webpack has introduced something about this in
https://webpack.js.org/guides/typescript/
And I have try this myself in
https://github.com/reactpersopnal/webpack-root/tree/feature/typescript
The reason is that you would like to use non-code assets with TypeScript, so we need to defer the type for these imports for webpack.
Your could simply add custom.d.ts.
declare module "*.jpg" {
const content: any;
export default content;
}

React & FuseBox alias settings - Absolute Paths

I am using React with FuseBox as bundler. The issue I am having at the moment is that aliasing isn't working so I can help deal with relative path hell.
My structure of the project:
stores folder has my MobX stores and an index.ts file that exports all the stores.
services has a bunch of service classes all exported in there respective files (no index.ts)
So in my fuse.ts I have:
alias: {
"services": "~/services",
"stores": "~/stores"
},
Then in my ui folder for example I am importing like so:
import AccountStore from "stores";
I get [ts] Cannot find module 'stores' error on that line at "stores".
Not sure have I got the alias section wrong? My homeDir in fuse.ts is set to "src/". I don't have any paths or baseUrl set in tsconfig like I did have when we were using webpack to setup absolute paths. Not sure if those are needed again or if it is something I am doing wrong with alias.
Any tips would be great :)
I have looked at the alias documentation on the fusebox site and followed it and tried a few different combinations but not getting any closer to it working. Would love some examples from people who have got this working.
Edit:
I have additionally done the following while trying to figure this out:
remove .fusebox folder
restarted vscode
have checked the bundle and it is adding a tilde there so fusebox must be recognising it?
will continue to add more things I try..
My solution to the problem I was having was to put the tsconfig.json file inside my src folder and the project/app inside ~.
Inside tsconfig.json i set baseUrl to root.
{
"compilerOptions": {
"baseUrl": ".",
// ...
}
}
This then allowed me to do absolute imports that would be the same across all files so it would be easy to reuse imports and quickly copy if needed.
import { service1, service2, service3 } from '~/services';
import { store1, store2 } from '~/stores';
The tilde usually represents home or base on a lot of systems so a few devs agreed it would be appropriate to use it in our folder structure. Though did have to remember to remove ~ from .gitignore if you have something that is autogenerated and its automatically in there.

Improve a react component's webpack configuration

I am quite newbie with React and Webpack, so I have a (maybe trivial) question:
I have recently created the react-scroll2top-button component.
What I don't like, though is the fact that my users have to provide the following configuration:
.jsx
import Scroll2TopButton from 'react-scroll2top-button/Scroll2TopButton';
webpack.config.js
module: {
loaders: [
{
...,
include: [path.resolve(__dirname, 'node_modules/react-scroll2top-button/Scroll2TopButton')],
...
}
]
}
Is there any optimal way to get rid of this ugly configuration?
I would like my users to be able to use my component by just importing it, like:
import Scroll2TopButton from 'react-scroll2top-button';
and nothing more.
I used the term "ugly", since I am almost sure that there is a way to fix this, after having seen that this is the way the rest of react components work. Maybe I am missing something really crucial, but that's why I came here, to also learn the proper way of doing this, since I have already done it twice and I think it is not that handy.
Thodoris
Your package is missing an entry point.
Add an index.js file and export Scroll2TopButton as default:
import Scroll2TopButton from './Scroll2TopButton.jsx';
export default Scroll2TopButton;
Or simply rename Scroll2TopButton.jsx to index.js.

Including an external js script in a React Component

I have a react application, managed using react-scripts.
In my app i am using an external js script. The external script doesn't do any module exports.
The structure of the external script is as below (too big to include it in full).
var TradingView = {.... various functions }
At the end of the file:
if (window.TradingView && jQuery) {
jQuery.extend(window.TradingView, TradingView)
} else {
window.TradingView = TradingView
}
My goal is to create a simple react component using the external script, and call the function: TradingView.widget({...});
I have been searching online for ways to include an external script in a react component/ES6 style, and have tried various options: react-async-script-loader, and various webpack plugins: script-loader, imports-loader, ProvidePlugin etc. But i haven't been able to make it work.
The error i am getting after using the imports-loader or ProvidePlugin is:
1189:31 error 'jQuery' is not defined no-undef
1190:9 error 'jQuery' is not defined no-undef
In my webpack config, i have:
In the loaders section:
{
test: /tv\.exec\.js/,
loader: 'imports?jQuery=jquery,$=jquery,this=>window'
}
In the plugins section:
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
When i create a simple webpage (no react), and include the script, and call TradingView.widget(), the page just works fine.
The closest i could get help was to look at:
Managing jQuery plugin dependency in webpack
But it didn't work for me. I am quite new to the react, webpack ecosystem, so I am not sure what i am missing here.
Please let me know if you need any additional info.
Update: I tested the above, including the script in a simple react component, but not using the react-scripts this time, and directly using webpack configurations. I was simply able to import the external js in my component directly, and it worked. I was also able to use imports-loader plugin in webpack to expose jQuery, which also worked. So its possible that using react-scripts needs something else to make it work.
It looks like your external script is handling its "exports" by adding them as members of window. You can use the import keyword on a file that doesn't define exports like so:
import "modulename";
There's nothing special about that syntax except that it doesn't imply that any functions or variables will be made available via the import facility. The code in "modulename" that assigns members to .window will execute, which is the important thing.
For compiler complaints about accessing window.* globals, try assigning the variable you want to access to a local variable:
const jquery = window.jquery;
...or maybe...
const TradingView = window.TradingView;
Then you'll have the variable in scope, and it should be usable.

Resources