TypeScript with Relay: Can't resolve generated module - reactjs

In my MessageItem.tsx component I have the following code:
const data = useFragment(
graphql`
fragment MessageItem_message on Message {
date
body
}
`,
message as any
);
After running relay-compiler --src ./src --schema ../../schema.graphql --language typescript --artifactDirectory ./src/__generated__, a module named MessageItem_message.graphql.ts gets generated.
But when I run the app it gives me an error:
Failed to compile.
./src/components/MessageItem.tsx
Module not found: Can't resolve
'./__generated__/MessageItem_message.graphql'
The reason is only components at the src root can refer to the right path (./__generated__), whereas components in a folder actually need to refer to the path (../__generated__) but it's not doing so.
How can I configure the path?

Edit .babelrc to point to the artifactDirectory
// .babelrc
{
"plugins": [
[
"relay",
{
"artifactDirectory": "./src/ui/graphql/types"
}
]
]
}

Remove "--artifactDirectory ./src/__generated__" from the relay-compiler options.
By default it seems the Relay compiler puts a "__generated__" directory in the directory with any source code containing GraphQL.
As a result any "./__generated__" references anywhere and at any level in the source code hierarchy now work as they should.
Thanks to #ThibaultBoursier for the pointer.
PS I wonder if the --artifcactDirectory option is just meant to be used to change the name of the artifact directory, rather than its location?

Just moments ago I ran into the same issue. The reason is that the relay-compiler is using the artifactDirectory setting to decide where to put the generated files, but the babel-plugin-relay exposing the graphql tag needs to get the very same argument otherwise it just attempts to include a colocated relative file.
I fixed it in my case by configuring the plugin with a babel-plugin-macros.config.js file as follows (where the artifactDirectory is the same as the one supplied to the relay-compiler):
module.exports = {
relay: {
artifactDirectory: "./src/ui/graphql/types",
},
};
This solution assumes you are using the macro via babel-plugin-macros, otherwise you might need to supply that argument via the .babelrc file but I have no experience with that unfortunately.

Related

RelayFindGraphQLTags failing to compile even though requirements are satisfied

I am attempting to compile Relay, however it is not recognizing my graphql queries as valid.
Sample query:
const testQuery = graphql`query CustomersQuery {
customers(first: 20) {
nodes {
id
name
}
}
}`
The project is on CRA 2.0 with Typescript.
The build script is as follows:
"relay": "relay-compiler --src ./src --schema ./schema.graphql --language typescript --extensions ts tsx js jsx"
And here is the error I received:
Parse error: Error: RelayFindGraphQLTags: Operation names in graphql tags must be prefixed with the module name and end in "Mutation", "Query", or "Subscription". Got `CustomersQuery` in module `Main`.
Does anyone know why this is happening? It feels like a bug.
Found the answer here. Basically says the the name of your query must be your filename + "Query". So for App.tsx the name of the query would have to be "AppQuery".
Note that the name of the query must be <FileName>Query. So query clientQuery { ... } will only work if the query is in a file named client.js.

How to read xml file(toolsbox.xml) in React typescript

I am unable to import xml file in tsx file, but in jsx file i can able to access that xml file
You need to define a module for typescript to evaluate, otherwise it will try to look for something like toolbox.xml.ts.
Something along these lines in a file called XML.d.ts (for this placed in a folder #types in src):
declare module "*.xml" {
const doc: any; // Change this to an actual XML type
export default doc;
}
and add "typeRoots": ["src/#types", "node_modules/#types"] to your tsconfig.json (this makes typescript pick up the new typings file along with all installed types).
I have the same issue and am not sure how this works; I cannot even solve a simple txt file import issue. In my case, my target is esnext and ESM modules

Is it good to use package.json file in react component file?

I have to use version mentioned in package.json file in front-end(react js) file.
{
"name": "asdfg",
"version": "3.5.2", // want to use this
"description": "description",
"scripts": {}
//etc etc etc
......
}
Send package.json [version] to Angularjs Front end for display purposes
I'd gone through above post and found two ways for the same. but none of them I was asked to implement.
#1. During build process
#2. By creating endpoint
So I want to know the approach below is valid/good or not ?
react-front-end-file.js
import packageJson from '../package.json'; // imported
...
...
// Usage which gives me version - 3.5.2
<div className='app-version'>{packageJson.version}</div>
Let me know if this approach is fine.
The below 2 approaches seems to have either dependency or add an extra implentation which might not be needed
During build process - ( has dependency on module bundler like webpack etc.)
By creating endpoint - ( needs an extra code at server just to get version )
Instead, As package.json is a file which takes json object in it so you can use it to import json and use its any keys mentioned in that file ( version in your case but only constraint here is, you should have access to package.json file after application deployment, so dont forget to move file in deployment environment )
So your approach seems to be fine.
I would do something like this:
In your module bundler, require your package json file and define a global variable and use it wherever you want
e.g. I do something like this in webpack:
const packageJson = require('./package.json')
const plugins = [
new webpack.DefinePlugin(
{
'__APPVERSION__': JSON.stringify(packageJson.version)
}
)
]
React Component:
<div className='app-version'>{__APPVERSION__}</div>

How to not show warnings in Create React App

I'm using create-react-app from Facebook, when it starts via 'npm start' it shows me a list of warnings, such as:
'Bla' is defined but never used
Expected '===' and instead saw '=='
I don't want to see any of these warnings, is there a way to supress them?
For local Eslint, add a file to your project named .eslintignore and add any directories or files you want to ignore:
build/
src/
*.js
Though you might as well remove it entirely at this point.
This doesn't work with building or starting the code however, if you are using create-react-app. There is no way to disable Eslint without ejecting because it's built into react-scripts. Anytime any you build or start the server, it will run eslint using its internal configs aside from special cases defined in package.json. The only way around that is to eject or prepend each file with the disable comment as mentioned elsewhere. See this issue on Github for more information.
Those warnings come from eslint. To disable them add /* eslint-disable */ at the top of the file you don't want to follow the eslint rules.
For specific eslint warning supression insert the following code at the beginning of the file.
/* eslint-disable react/no-direct-mutation-state */
My rep is not high enough to comment on #fly's excellent answer, so I'll C+P it to add this instead:
For anyone looking for a temporary but quick and effective workaround for disabling console warnings from DevTools, this might do the trick.
Disclaimer - this might not work on versions that are not mine(react-scripts v3.0.1, react-dev-utils#^9.0.1), so use it at your own risk.
enter this directory
node_modules/react-dev-utils/webpackHotDevClient.js
look for this function(should be around line 114)
function handleWarnings(warnings) {
either add the return at the start of function printWarnings() (line 124), or comment out the call to printWarnings() in line 145.
restart, eg with npm run start, for change to take effect.
This way, the hot reloader continues to work, but the annoying warnings which have already been caught in my editor are not output in the browser.
Recently the ability to add your own editor configurations was added, this can be used to "partially" disable the functionality of ESLint. You just need to create a configuration file in the root directory.
.eslintrc:
{
"parser": "babel-eslint"
}
.env
SKIP_PREFLIGHT_CHECK=true
If you create a new application, it will by default come with a pre-filled eslintConfig object in the package.json
To Completely Remove eslint warnings, what you can do is create a file named .eslintignore add * and save it. You wont see any more warning.
*
To Remove warnings from a particular folder means in the .eslintignore file add that folder name
/folder_name
/folder_name/file_name.js
You can also do this in the file level also. Add the following in the beginning of the file
/* eslint-disable */
To ignore the next line warning in a file
// eslint-disable-next-line
If you want to disable warnings in DevTools
Open the Console Tab.
Default levels/Custom levels -> uncheck Warnings
Set the DISABLE_ESLINT_PLUGIN environment variable:
DISABLE_ESLINT_PLUGIN=true npm start
For anyone looking for a temporary but quick and effective workaround for disabling console warnings from DevTools,
this might do the trick.
Disclaimer - this might not work on versions that are not mine(react-scripts v3.0.1, react-dev-utils#^9.0.1),
so use it at your own risk.
enter this directory
node_modules/react-dev-utils/webpackHotDevClient.js
look for this function(should be around line 114)
function handleWarnings(warnings) {
and add a return statement right after it.
Your code should end up looking like this(if you're using webstorm)
That should shut the webpackHotDevClient.js:{whateverLineIdontCare} right up.
Cheers.
If you're using create-react-app, then you can go into the package.json and edit the eslintConfig value. I just wanted to disable the "eqeqeq" and "no-unused-vars" rules, so mine looks like this:
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
],
"rules": {
"eqeqeq": "off",
"no-unused-vars": "off"
}
},
You'll have to re-run npm start for it to take effect.
Add a .eslintignore file and add
src/*
You can read more about this at
https://eslint.org/docs/user-guide/configuring/ignoring-code
https://eslint.org/docs/user-guide/configuring/rules
You can use craco and configure craco.config.js for example
module.exports = {
webpack: {
configure: (webpackConfig) => {
const ignoreWarnings = [{ module: /some module/, message: /some message/ }]
return { ...webpackConfig, ignoreWarnings }
}
}
}
more details here
You can disable the typescript and/or linting errors with setting the environment variables in .env
TSC_COMPILE_ON_ERROR,
ESLINT_NO_DEV_ERRORS, to true
more information on advanced configuration for create react app on
https://create-react-app.dev/docs/advanced-configuration/
This is a simple way I avoid seeing unused variable warnings when debugging:
import someVariable from "./wherever"
// Prevent unused variable warnings
while (false) {
console.log(someVariable)
}

Flow seems not to respect include option?

I've setup my React project with a folder for common components I want to import directly.
src/
---components/
---common/
---/TextInput
---/TabSelector
Full folder structure from root
Each of these folders in common have a index.jsx (and other resources such as style etc) with and export default <name> statement.
So my webpack config has the following configuration:
resolve: {
modulesDirectories: [
'node_modules',
myCommonComponentsPath
]
}
which allows direct imports: import TextInput from 'TextInput'
Trying to add this to .flowconfig (according to flow's documentiation) is not working though:
[include]
./node_modules/
<PROJECT_ROOT>/src/components/common
This works with webpacks resolver (components load and work) but flow gives the following error:
9: import TextInput from 'TextInput';
^^^^^^^^^^^ TextInput. Required module not found
Any help would be appreciated.
How do I resolve this?
You need to use the module.system.node.resolve_dirname setting, which is different from the include setting. Since you are telling Webpack a new place to find modules, you also need to tell Flow about that new place.
[options]
module.system.node.resolve_dirname=node_modules
module.system.node.resolve_dirname=src/components/common
The paths are relative to the location of your '.flowconfig' file.

Resources