"babel-plugin-react-intl" is not working as expected - reactjs

I have created my react app using create-react-app command. Now I would like to available my website in both hindi and english language.
So for that I am using yahoo/react-intl. I have also installed the babel-plugin-react-intl plugin. Also added the .babelrc file.
My .babelrc file look like:
{
"presets": ["es2015", "react"],
"plugins": [
[
"react-intl",
{
"messagesDir": "./build/messages/"
}
]
]
}
But I am not getting the extracted messages from my js file to ./build/messages/.
I dont know where I made a mistake.
My index.js is:
import React from "react";
import ReactDOM from "react-dom";
import { IntlProvider, addLocaleData } from "react-intl";
import hi from "react-intl/locale-data/hi";
import en from "react-intl/locale-data/en";
import registerServiceWorker from "./registerServiceWorker";
import Hello from "./components/Hello";
addLocaleData([...en, ...hi]);
ReactDOM.render(
<IntlProvider locale="hi" messages={/*comming soon*/}>
<Hello />
</IntlProvider>,
document.getElementById("root")
);
registerServiceWorker();
And all my js-files are inside the components folder.
Foe example my Hello.js component looks like:
import React, { Component } from "react";
import { FormattedMessage } from "react-intl";
class Hello extends Component {
render() {
return (
<div>
<h1>
<FormattedMessage id="Hello.heading" defaultMessage="Hello world" />
</h1>
<p>
<FormattedMessage
id="Hello.paragraph"
defaultMessage="This is my world"
/>
</p>
</div>
);
}
}
export default Hello;
My package.json is:
{
"name": "i18n-myexamplae",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-intl": "^2.4.0",
"react-scripts": "1.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"babel-plugin-react-intl": "^2.4.0"
}
}

This is because react-scripts don't use your .babelrc. You either need to eject because then you're allowed to edit .babelrc config or you need to run babel manually.
Run ./node_modules/.bin/babel src --out-dir lib and ignore/delete everything in --out-dir. You're doing this only to extract messages. Also, to make build consistent, replace your es2018 and react presets with react-app preset, which is the one used by create-react-app.
NOTE: when using react-app preset you actually need to run NODE_ENV=development ./node_modules/.bin/babel src --out-dir lib, because react-scripts require NODE_ENV to be configured. You can add this to you package.json to make things easier.
"scripts": {
"extract": "NODE_ENV=development babel src --out-dir lib",
...
},
I faced a similar issue in i18n library I'm writing, lingui. lingui extract command is checking if a project uses create-react-app and if so, it uses react-app preset automatically for extracting messages.

Related

Error when importing JSX files from another package in monorepo with React

I created a simple project to study monorepo. The example consists of three React applications, where one consists of a lib of components with the Storybook and the other two will import the components of this package.
However I am not able to import a component from another package.
When I import a common function, no error occurs.
Github repository
Error message
../components/src/button/Button.js
SyntaxError: /home/thiago/Documentos/Dev/projects/learn-monorepo/packages/components/src/button/Button.js: Support for the experimental syntax 'jsx' isn't currently enabled (7:5):
5 | function Button({label, ...rest}) {
6 | return (
> 7 | <div>
| ^
8 | <button {...rest}>
9 | {label}
10 | </button>
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
Button component
function Button({label, ...rest}) {
return (
<div>
<button {...rest}>
{label}
</button>
</div>
);
}
export { Button };
App.js
import React from 'react';
import { Button } from '#project/components';
function App() {
return (
<div>
<h1>Hello World - App 01</h1>
<Button label="Button"/>
</div>
);
}
export default App;
Package.json
{
"name": "project",
"version": "1.0.0",
"main": "build/index.js",
"author": "thiago <thenrique2012#gmail.com>",
"license": "MIT",
"private": true,
"workspaces": {
"packages": ["packages/*"]
},
"babel": {
"presets": [
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-syntax-jsx"
]
},
"scripts": {
"bootstrap": "lerna bootstrap",
"start:app-01": "lerna run --scope #project/app-01 start",
"start:app-02": "lerna run --scope #project/app-02 start",
"start:storybook": "lerna run --scope #project/components storybook",
"start:web": "yarn start:app-01 & yarn start:app-02 & yarn start:storybook"
},
"devDependencies": {
"#babel/plugin-syntax-jsx": "^7.12.1",
"#babel/preset-react": "^7.12.10",
"babel-loader": "8.1.0",
"lerna": "^3.22.1"
}
}
You get error because you have not transpiled your shared react components. There are some (not official) solutions for this with create-react-app. One of them is to use react-app-rewired and customize-cra. Instal lthem as dev-dependency and add a config-overrides.js file to the root of your create-react-app:
var path = require('path')
const { override, babelInclude } = require('customize-cra')
module.exports = function (config, env) {
return Object.assign(
config,
override(
babelInclude([
/* transpile (converting to es5) code in src/ and shared component library */
path.resolve('src'),
path.resolve('../components'),
])
)(config, env)
)
}
Then use react-app-rewired instead of react-scripts in your scripts for start and build of the project:
"scripts": {
"start": "react-app-rewired start",
"build-prod": "react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},

ReactJS markdown editor component fails to render

I'm learning React at the moment, and I am currently trying out the Slate Markdown Editor in CodeSandbox. I am trying to initialize a Slate Editor instance like this:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import Editor from "slate-md-editor";
const MdEditor = Editor();
<MdEditor />;
However, CodeSandbox displays the following error when I attempt to compile my code:
at evaluate (https://oxxbg.csb.app/node_modules/canner/slate-icon-codeblock/lib/index.js:80:45z
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:98419
X.evaluate
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110543
ye.evaluateTranspiledModule
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:120123
c
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110289
evaluate
https://oxxbg.csb.app/node_modules/slate-md-editor/lib/index.js:34:27
z
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:98419
X.evaluate
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110543
ye.evaluateTranspiledModule
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:120123
c
https://codesandbox.io/static/js/sandbox.cddc3c052.js:1:110289
evaluate
/src/index.js:5
2 | import ReactDOM from "react-dom";
3 | import "./styles.css";
4 |
> 5 | import Editor from "slate-md-editor";
6 | const MdEditor = Editor();
7 |
8 | <MdEditor />;
I have not experienced this previously, and I am at a loss of knowing what to do.
I would greatly appreciate it if someone more experienced has some idea of this issue. Thank you in advance.
Link to the Sandbox
This is my package.json:
{
"name": "slate-editor",
"version": "1.0.0",
"description": "React testing project",
"keywords": [
"react",
"starter"
],
"main": "src/index.js",
"dependencies": {
"antd": "4.10.2",
"immutable": "4.0.0-rc.12",
"react": "17.0.0",
"react-dom": "17.0.0",
"react-scripts": "3.4.3",
"slate": "0.59.0",
"slate-md-editor": "1.5.4",
"slate-react": "0.59.0",
"slate-schema-violations": "0.1.39"
},
"devDependencies": {
"typescript": "3.8.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Here is what I found out later:
Step 1
Setup a basic React project like so:
npx create-react-app slate-editor-demo
cd slate-editor-demo
Step 2
Delete the App.js, App.testing.js, and App.css in the src/ folder. You should now only have five files in that folder:
index.css
index.js
logo.svg
reportWebVitals.js
setupTests.js
Step 3
Install dependencies for slate-md-editor. Here they are:
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"antd": "^3.8.4",
"immutable": "^3.8.2",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-scripts": "1.1.5",
"slate": "^0.40.2",
"slate-react": "^0.12.0",
"slate-schema-violations": "^0.1.39",
"slate-md-editor": "1.5.4",
"web-vitals": "^1.0.1"
You can simply copy these dependencies into your package.json, and then run npm install to update the deps.
Step 4
Edit your src/index.js to look something like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Editor from "./slateMDEditor";
import reportWebVitals from './reportWebVitals';
const options = {
// default settings
prismOption: {
// https://github.com/GitbookIO/slate-prism
onlyIn: node => node.type === 'code_block',
getSyntax: node => node.data.get('syntax')
},
codeOption: {
// https://github.com/GitbookIO/slate-edit-code
onlyIn: node => node.type === 'code_block'
},
blockquoteOption: {
// https://github.com/GitbookIO/slate-edit-blockquote
},
listOption: {
// https://github.com/GitbookIO/slate-edit-list
types: ['ordered_list', 'unordered_list'],
typeItem: 'list_item',
typeDefault: 'paragraph'
}
}
const MdEditor = Editor(options);
ReactDOM.render(
<MdEditor onChange={this.onChange} />,
document.getElementById('root')
);
// Start measuring performance in app
reportWebVitals();
Step 5
Last step: run npm run start (if you use NPM), or yarn start (if you use yarn). You should see slate markdown editor running smoothly in your browser on localhost.

How to put FontAwesome icons in react?

I created one React project and I am trying to put FontAwesome icons in react project, but it is showing some syntax errors so help me to resolve this issue.
This is package.json file
{
"name": "icons",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.25",
"#fortawesome/free-brands-svg-icons": "^5.11.2",
"#fortawesome/free-regular-svg-icons": "^5.11.2",
"#fortawesome/free-solid-svg-icons": "^5.11.2",
"#fortawesome/react-fontawesome": "^0.1.7",
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-scripts": "3.2.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
This is index.js file
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faCoffee } from '#fortawesome/free-solid-svg-icons'
const element = <FontAwesomeIcon icon={faCoffee} />
ReactDOM.render(<App />, element, document.getElementById('root'));
serviceWorker.unregister();
I am getting error like this Error: Target container is not a DOM element.
You got a little confused with rendering your React code into the DOM.
React.render() takes 2 parameters, the first is your React element, and the second is the target in your index.html file, whereas you have added 3 parameters, hence the error.
You would need to create a React stateless functional component in this scenario, called App:
function App() {
return (
<div>
<FontAwesomeIcon icon={faCoffee} />
</div>
)
}
And now the jsx component is now available as per your existing code, so you can use:
ReactDOM.render(<App />, document.getElementById('root'));
Sources: https://reactjs.org/docs/components-and-props.html
If you're not rendering the icon in App, you can render it by itself directly:
const element = <FontAwesomeIcon icon={faCoffee} />
ReactDOM.render(<div>{element}</div>, document.getElementById('root'));
But as Kraylog pointed out you are not using the ReactDOM.render method correctly. You can read about it here.
As to your "I am getting error like this Error: Target container is not a DOM element." Error, you need to make sure that in your index.html file there is a div with an id of root like such <div id="root"></div>. ReactDOM (which is imported from import ReactDOM from "react-dom";) has a render method on it that converts your React code to plain JavaScript and then inserts it into the real DOM. The render method ONLY NEEDS TWO arguments to work, however a third argument can be used as a callback function like such ReactDOM.render(element, container, () => console.log("Application Mounted in DOM")), but I've never seen anyone use the callback function. You can read more about it here on the official document website ReactDOM.render, or you can watch a pretty decent video on it on YouTube here
Here are some further tips on using the icons in a reusable manner.
Follow these steps taken from the #fortawsome npmjs registry
Install the necessary packages for the cause
$ npm i --save #fortawesome/fontawesome-svg-core
$ npm i --save #fortawesome/free-solid-svg-icons
$ npm i --save #fortawesome/react-fontawesome
$ yarn add #fortawesome/fontawesome-svg-core
$ yarn add #fortawesome/free-solid-svg-icons
$ yarn add #fortawesome/react-fontawesome
Install some MORE of the free stuff in that they were nice enough to provide :)
$ npm i --save #fortawesome/pro-solid-svg-icons
$ npm i --save #fortawesome/pro-regular-svg-icons
$ npm i --save #fortawesome/pro-light-svg-icons
$ npm i --save #fortawesome/pro-duotone-svg-icons
Install even more if you are a paid pro member
$ npm i --save #fortawesome/pro-solid-svg-icons
$ npm i --save #fortawesome/pro-regular-svg-icons
$ npm i --save #fortawesome/pro-light-svg-icons
$ npm i --save #fortawesome/pro-duotone-svg-icons
Usage
Now, finally to the good part of actually using it in an application.
I'm going to create a wrapper component around it, so that it's easy to reuse the icon/component later on, and in order to do this start by creating a file called CoffeeIcon.js, and in that file put in something along the lines of the following:
import React from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faCoffee } from "#fortawesome/free-solid-svg-icons";
import PropTypes from "prop-types";
const CoffeeIcon = props => {
return (
<React.Fragment>
{props.labelText ? <label>{props.labelText}</label> : null}
<FontAwesomeIcon
icon={faCoffee}
style={props.styles}
id={props.id}
className={props.className}
/>
</React.Fragment>
);
};
CoffeeIcon.propTypes = {
labelText: PropTypes.string,
id: PropTypes.string,
className: PropTypes.string,
styles: PropTypes.object
};
export default CoffeeIcon;
If you plan on using PropTypes for type checking and validation then add it to your application like such:
yarn add prop-types or npm i prop-types
And Finally, back in your component where you desire to use it, just do the following:
import it and place it just below your other import statements:
import CoffeeIcon from "../Components/CoffeeIcon";
Drop in the component where you desire:
<CoffeeIcon
styles={{ color: "maroon" }} // optional
id={"coffee-wrapper-id" || null} // optional
className={"coffee-wrapper-class" || null} // optional
labelText={"Coffee Icon"} // optional
/>
You're done and can now EASILY reuse it!

Module not found: Can't resolve 'react-native'

I moved from npm to yarn and for some reason, although I imported the react-native library it doesn't recognize it, I get the error:
./src/App.js
Module not found: Can't resolve 'react-native' in '/var/react-projects/gymgains/src'
I delete the package.json.lock, also yarn.lock and tried again:
yarn
Yet it didn't solve the problem.
Here is my package.json:
{
"name": "App",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.3",
"react-dom": "^16.8.3",
"react-firebase-file-uploader": "^2.4.2",
"react-native": "^0.58.5",
"react-native-cli": "^2.0.1",
"react-scripts": "2.1.5"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
And here is my import statements:
import React, { Component } from 'react';
import firebase from 'firebase';
import { Text, View, Image } from 'react-native';
import 'firebase/firestore';
import FileUploader from 'react-firebase-file-uploader';
Is there a difference between running it with 'yarn start' to see it in the browser and push it to an Android to test it in the simulator, could that be the problem that react-native does not work in the web browser?
Any idea how to solve this issue?
Thanks
I had some very similar issue:
Module not found: Can't resolve 'react-native'
and in my case it helped me to do
yarn add react-native-web
As you do not have that module installed. You could give it a try.
Can you try npm install and see. I think your node_modules does not have react-native package.

Create React App executing tests with jest Unexpected token import

I am just a new developer on React. I have just starting a new app using the create-react-app plugin. After that I have customised my own App Component, but this is using some third party components which makes the npm run test (react-scripts test --env=jsdom) fails with an error:
SyntaxError: Unexpected token import
This error only happens for an import inside a dependency at node_modules I am using. For example, it gives no error on
import React, { Component } from 'react';
Since I am using the create-react-app plugin I do not know what I need to change to make it pass. However, it seems to be something related with some babel configurations missing.
I think I should not need to install babel-jest dependency since that is embedded with create-react-app.
I have also tried to execute, without success:
npm run test -- --no-cache
The package.json file:
{
"name": "dhis2-hello-world",
"version": "0.1.0",
"private": true,
"dependencies": {
"d2": "^28.3.0",
"d2-manifest": "^1.0.0",
"d2-ui": "^28.0.8",
"d2-utilizr": "^0.2.15",
"loglevel": "^1.6.0",
"material-ui": "^0.20.0",
"prop-types": "^15.6.0",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.0.17",
"rxjs": "^5.5.5"
},
"scripts": {
"prestart": "d2-manifest package.json ./public/manifest.webapp",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"manifest.webapp": {
"name": "DHIS2 App Template",
"description": "DHIS2 App Template",
"icons": {
"48": "icon.png"
},
"developer": {
"url": "",
"name": "DHIS2"
},
"activities": {
"dhis": {
"href": ".."
}
}
}
}
The error:
/node_modules/d2-ui/lib/app-header/HeaderBar.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import PropTypes from 'prop-types';
PropTypes is being imported on a component at d2-ui which is being import at App component like this:
import React, { Component } from 'react';
import HeaderBarComponent from 'd2-ui/lib/app-header/HeaderBar';
I was looking for a way to solve it without need to eject the project.
Could anyone give me some clues of how to solve that problem?
Many thanks!

Resources