How do I get version number from package.json in react [duplicate] - javascript

This question already has answers here:
Get version number from package.json in React Redux (create-react-app)
(6 answers)
Closed last month.
I have this plugin version number in package.json file that I am trying to get but I was unable to import package.json. I am getting this error "Module not found: You attempted to import /package.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported."
import React from "react";
import { withTaskContext } from "#twilio/flex-ui";
import "./styles.css";
import TextField from "#material-ui/core/TextField";
import FormControl from "#material-ui/core/FormControl";
import Button from "#material-ui/core/Button";
import PropTypes from "prop-types";
import DropDown from "../style/dropdown";
import packageJson from "/package.json";
class VoiceCallComponent extends React.Component {
...
...
console.logh("version number ", packageJson.version);
}
This is my package.json
{
"name": "plugin-sample",
"version": "1.0.0",
"private": true,
"scripts": {
"postinstall": "flex-plugin pre-script-check"
}
}

I am not sure what you are trying todo.
But maybe this helps you getting the version (using require here)
var packageJson = require('./package.json'); console.log(packageJson.version)
Edit: Does not work for react because of compiling. But I referenced a great working solution in the comments which also does not expose your package.json.

If you're just looking to read the package.json into the project only once. You can use the bundler to define a constant that's automatically replaced with the configured value at compilation. Then you just import the package.json into the bundler's config file.
import package.json into bundler config:
import pkgJSON from "./package.json" // add to vite or webpack config
Vite define: vite.config.js:
export default {
// ...
define: {
"__PACKAGE_JSON_VERSION__": JSON.stringify(pkgJSON.version)
}
// ...
}
Webpack DefinePlugin: webpack.config.js:
new webpack.DefinePlugin({
"__PACKAGE_JSON_VERSION__": JSON.stringify(pkgJSON.version),
})
Then just use the constant in you components:
import React from "react";
import { withTaskContext } from "#twilio/flex-ui";
import "./styles.css";
import TextField from "#material-ui/core/TextField";
import FormControl from "#material-ui/core/FormControl";
import Button from "#material-ui/core/Button";
import PropTypes from "prop-types";
import DropDown from "../style/dropdown";
class VoiceCallComponent extends React.Component {
...
...
console.log("version number ", __PACKAGE_JSON_VERSION__);
}
Hope this helps.

Related

Standard Way for React Import Statements

I was wondering if there's a standard way to write import statements in react? For example, I have this:
import React, { useState, FormEvent } from 'react';
import Avatar from '#material-ui/core/Avatar';
import {Grid, Checkbox, TextField, FormControlLabel, CssBaseline} from '#material-ui/core';
import LockOutlinedIcon from '#material-ui/icons/LockOutlined';
import { LOGIN } from '../../graphql/mutations/login';
import { schema } from '../../helpers/validations/login';
import { Redirect } from 'react-router-dom';
import { useMutation } from '#apollo/react-hooks';
import StatusMessage from '../../helpers/statusMessages/loginMessage';
import Copyright from '../../components/copyright/copyright';
import CustomButton from '../../components/button/button';
import { ExecutionResult } from 'graphql';
import { Wrapper, StyledLink, Form, StyledTypography, StyledBox, StyledContainer} from './styles';
import { store } from '../../store';
import { useDispatch } from 'react-redux';
import SignInResponse from '../../graphql/responses/login';
import { useFormik } from 'formik';
Are there any rules about whether I should import everything from '#material-ui/core';separately or together? Does it make a difference apart from reducing the number of lines?
Is there any rule about if I should import other local files/functions after react's own libraries/content? Any other rules/suggestions?
There are known standard, most of them are opinions rather than must-dos. I would recommend that you take a look at eslint-plugin-import as it has a extensive list of standards/opinions regarding imports:
Ensure all imports appear before other statements ([first])
Ensure all exports appear after other statements ([exports-last])
Report repeated import of the same module in multiple places ([no-duplicates])
Forbid namespace (a.k.a. "wildcard" *) imports ([no-namespace])
Ensure consistent use of file extension within the import path ([extensions])
Enforce a convention in module import order ([order])
Enforce a newline after import statements ([newline-after-import])
Prefer a default export if module exports a single name ([prefer-default-export])
Limit the maximum number of dependencies a module can have ([max-dependencies])
Forbid unassigned imports ([no-unassigned-import])
Forbid named default exports ([no-named-default])
Forbid default exports ([no-default-export])
Forbid named exports ([no-named-export])
Forbid anonymous values as default exports ([no-anonymous-default-export])
Prefer named exports to be grouped together in a single export declaration ([group-exports])
Enforce a leading comment with the webpackChunkName for dynamic imports ([dynamic-import-chunkname])
Regarding the order, what's recommended is:
node "builtin" modules
"external" modules
"internal" modules
modules from a "parent" directory
"sibling" modules from the same or a sibling's directory
"index" of the current directory
There is no standard way, just personal preferences.
Personally, I prefer to group imports from a common source, like you did in '#material-ui/core';. You could also do that with components, helpers, and similar local modules. Also, I prefer to import first third-party modules and then local modules.
It's all about finding something "logical" and easy to scan to you.
Don't worry about how many lines were used to import modules. I think it's a best practice to first import modules from other vendors, then import local modules. There are some lint rules to enforce that I think.
Other than that, I'd say only import what is needed:
import Avatar from '#material-ui/core/Avatar';
is better than
import * as MaterialUI from '#material-ui/core';
No, there is no standard on how you import something. But instead of import everything just import what you need, it'll also help webpack in tree-shaking unused code. So I would suggest this:
import { Avatar } from '#material-ui/core';
One other I like to do is separate my local imports from the packages imports, it makes the code more readable:
import React, { useState, FormEvent } from 'react';
import LockOutlinedIcon from '#material-ui/icons/LockOutlined';
import { ExecutionResult } from 'graphql';
import { Avatar, Grid, Checkbox, TextField, FormControlLabel, CssBaseline } from '#material-ui/core';
import { Redirect } from 'react-router-dom';
import { useMutation } from '#apollo/react-hooks';
import { useDispatch } from 'react-redux';
import { useFormik } from 'formik';
import { LOGIN } from '../../graphql/mutations/login';
import { schema } from '../../helpers/validations/login';
import { store } from '../../store';
import { Wrapper, StyledLink, Form, StyledTypography, StyledBox, StyledContainer } from './styles';
import StatusMessage from '../../helpers/statusMessages/loginMessage';
import Copyright from '../../components/copyright/copyright';
import CustomButton from '../../components/button/button';
import SignInResponse from '../../graphql/responses/login';

How to avoid import everything that the component needs in each test file?

In my jest tests, I need to import everything that the tested component needs to work (which I do in my application's main.js). Since I have multiple test files, I need to "re-import" it in each file. Is there a way to import it all in a single file, and then import only this file?
import Component from '#/views/input-something'
import {mount, shallowMount} from '#vue/test-utils'
import {FontAwesomeIcon} from '#fortawesome/vue-fontawesome'
import {library} from '#fortawesome/fontawesome-svg-core'
import {fas} from '#fortawesome/free-solid-svg-icons'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import 'bootstrap/dist/css/bootstrap.css'
import BootstrapVue from 'bootstrap-vue'
import 'vue-select/dist/vue-select.css'
import Vuelidate from 'vuelidate'
import Vue from 'vue'
import './helpers/multi-ref-test-runner'
Vue.component('font-awesome-icon', FontAwesomeIcon)
Vue.use(BootstrapVue)
Vue.use(Vuelidate)
library.add(fas)
// I wish to write everything above in a single file
window.confirm = function() { return false; }
describe('input-something', () => {
let wrapper;
beforeEach(() => {
wrapper = mount(Component, {...});
});
it('it renders', () => {});
});
I expect to import everything I need in a file, like helper.js
Then in my test file I'd just do something like
import 'test-helpers/helper';
describe('input-something', () => {...})
EDIT 1
After a while I was able to import all I needed this way
/* imports.js */
import Component from '#/components/something'
import { mount } from '#vue/test-utils'
export { Component, mount }
/* my-test.js */
import { Component, mount } from './imports.js'
And adding this line to my .babelrc (to be able to work with jest)
"plugins": ["#babel/plugin-syntax-dynamic-import"]
And then I could use all the properties I imported.
Although it's working this way, I wanted to use these properties (Component, mount...) without having to implicitly import each one.
Is there a way to do it?
create a separate js file
import components or plugins or anything you want there
import that file in main.js file
For example:
this is my separate reuseableComponets.js
// I include components and plugins here
...
import Component from '#/views/input-something'
import {mount, shallowMount} from '#vue/test-utils'
import {FontAwesomeIcon} from '#fortawesome/vue-fontawesome'
...
Now in app.js
import('path to reuseableComponets.js')
That's it.
Use setupFilesAfterEnv in your jest.config.js to point to a script that sets up your tests. This file would be automatically invoked before your tests, so you wouldn't have to import it.
For example, you could move the setup code you had mentioned into a file named my-setup.js, and then configure Jest as follows:
// jest.config.js
module.exports = {
setupFilesAfterEnv: ['./my-setup.js'],
}

Issue with import statement file paths

When I attempt to import my SearchBar component into App.js, it says that the module cannot be resolved.
I've been trying to figure this out for days so I assume I must be making a some kind of syntax error.
I've tried just using an export statement on the class declaration line for the SearchBar component class and then importing it into App.js using: Import { SearchBar } from './Components/SearchBar/Searchbar;'
Here is the code for SearchBar.js:
import React from 'react';
import './SearchBar.css';
class SearchBar extends React.Component {
render() {
return(<JSX Elmements>)
}
}
export default SearchBar;
Here is the import statement in App.js:
import SearchBar from './Components/SearchBar/SearchBar';
And this is the file structure:
SRC/
- App.js
- App.css
- Components/
- SearchBar/
- SearchBar.js
- SearchBar.css
This is the error message I get:
./src/App.js
Module not found: Can't resolve './Components/Searchbar/SearchBar' in '/home/runner/src'
The first SearchBar (directory) in your import has a lowercase b.
In your directory structure they are all CamelCase.
So it should be
import SearchBar from './Components/SearchBar/SearchBar';
here was the typo -------------------------------------------^

ReactDOM.render() unresolved

import React from 'react';
// import ReactDOM from 'react-dom';
import ReactDOM from 'react-dom/dist/react-dom.min';
import {Alert} from 'reactstrap';
class AlertLine extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
};
}
onDismiss = () => {
this.setState(
{
visible: false
}
);
};
render() {
return (
<div>
<Alert color="success" isOpen={this.state.visible} toggle={this.onDismiss}>
<strong>Success!</strong> You successfully read this important alert message.
</Alert>
</div>
);
}
}
ReactDOM.render(
<AlertLine/>,
document.getElementById('root')
);
ReactDOM.render() works just fine with 'react-dom' for development. However, as soon as I try import minified 'react-dom.min' instead of 'react-dom', render() goes unresolved and nothing happens. I can't find render() from content assist(ctrl + space) neither.
I've installed react#15.6.1 and react-dom#15.6.1 with npm and they're on 'npm list'. Then I tried reinstall them but that didn't work.
In your case, you have to use import ReactDOM from 'react-dom' because import doesn't mean "file import", it means "ES6 module import".
To minify your bundle file, try uglifyjs-webpack-plugin (if you're using webpack) or minifyify (if you're using browserify)
Non-module
Node modules loaded with require / import must populate an exports object with
everything that the module wants to make public.
stackoverflow.com/a/14914442/6836839
react-dom.min.js is used as a simple js library, you can't import / require
Install
Since you can't require / import, you need to load it as a normal js script:
<!-- index.html -->
<script src="node_modules/react-dom/dist/react-dom.min.js"></script>
Use
// Just call it...
ReactDOM.render(component, document.getElementById('root'))
Note
If you load React from a tag, these top-level APIs are available on the ReactDOM global.
If you use ES6 with npm, you can write import:
import ReactDOM from 'react-dom'
If you use ES5 with npm, you can write:
var ReactDOM = require('react-dom');
https://facebook.github.io/react/docs/react-dom.html
Import name is not same as the component name which you are exporting.
When you Import a component in a common Index.js file and you are Importing a component(import Header from './components/Header';).
Header should be different from export default headerComponent; name

Uncaught ReferenceError: React is not defined

I am trying to make ReactJS work with rails using this tutorial. I am getting this error:
Uncaught ReferenceError: React is not defined
But I can access the React object in browser console
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined
Can anyone suggest me on how to resolve this?
[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:
var Comment = React.createClass({
render: function () {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{this.props.comment}
</div>
);
}
});
var ready = function () {
React.renderComponent(
<Comment author="Richard" comment="This is a comment "/>,
document.getElementById('comments')
);
};
$(document).ready(ready);
And this is my index.html.erb:
<div id="comments"></div>
If you are using Babel and React 17, you might need to add "runtime": "automatic" to Babel config.
In .babelrc config file this would be:
{
"presets": [
"#babel/preset-env",
["#babel/preset-react", {"runtime": "automatic"}]
]
}
I got this error because I was using
import ReactDOM from 'react-dom'
without importing react, once I changed it to below:
import React from 'react';
import ReactDOM from 'react-dom';
The error was solved :)
I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json:
externals: {
'react': 'React'
},
This above configuration tells webpack to not resolve require('react') by loading an npm module, but instead to expect a global variable (i.e. on the window object) called React. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React exists).
If you are using Webpack, you can have it load React when needed without having to explicitly require it in your code.
Add to webpack.config.js:
plugins: [
new webpack.ProvidePlugin({
"React": "react",
}),
],
See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin
Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.
P.S
Possible solutions.
If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
Make sure you have the line import React from 'react';
Try to add:
import React from 'react'
import { render } from 'react-dom'
window.React = React
before the render() function.
This sometimes prevents error to pop-up returning:
React is not defined
Adding React to the window will solve these problems.
Adding to Santosh :
You can load React by
import React from 'react'
I know this question is answered. But since what worked for me isn't exactly in the answers, I'll add it here in the hopes that it will be useful for someone else.
My index.js file looked like this when I was getting Uncaught ReferenceError: React is not defined.
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Adding import React from 'react'; at the top of the file fixed it.
Now my index.js looks like this and I don't get any error on the console.
import React from 'react';
import {render} from 'react-dom';
import App from './App';
render(<App />, document.getElementById("root"));
Please note I made no change in webpack.config.js or anywhere else to make this work.
import React, { Component, PropTypes } from 'react';
This may also work!
If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".
I was facing the same issue.
I resolved it by importing React and ReactDOM like as follows:
import React from 'react';
import ReactDOM from 'react-dom';
I got this error because in my code I misspelled a component definition with lowercase react.createClass instead of uppercase React.createClass.
I got this error because I used:
import React from 'react';
while working with React, Typescript and Parcel
Changing it to:
import * as React from 'react';
Solved the problem as suggested by https://github.com/parcel-bundler/parcel/issues/1199#issuecomment-381817548
Sometimes the order of import can cause this error, if after you have followed all the steps above and still finds it hard on you, try making sure the react import comes first.
import React from 'react'
import { render } from 'react-dom'
before any other important you need to make.
The displayed error
after that import react
Finally import react-dom
if error is react is not define,please add ==>import React from 'react';
if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';
To whom using CRA and ended up to this question, can use customize-cra and react-app-rewired packages to override babel presets in CRA.
To do this, create a config-overrides.js in the root and paste this code snippet in it.
const { override, addBabelPreset } = require('customize-cra');
module.exports = override(
addBabelPreset('#emotion/babel-preset-css-prop'),
addBabelPreset([
'#babel/preset-react',
{
runtime: 'automatic',
importSource: '#emotion/react',
},
]),
);
And update scripts in package.json with the ones below.
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
I got this because I wrote
import react from 'react'
instead of
import React from 'react'

Categories