We're currently working on a school project and we have a part of the app that's kind of "external". (Just used for displaying a graph) So that /graph folder is now in the /src folder and when compiling the react app we get tons of import errors. Is there a way to bypass those imports and just use the global variables, which are already implemented?
3 Answers
Global variables in React can be implemented using webpack.config.js file.
Inside the webpack config file declare your global variable.
i.e. const API_URL = JSON.stringify('http://api:8080'); Also, you need to add new plugins to webpack, in order for this global variable to be accessible by your whole app.
new webpack.DefinePlugin({ //defining gloabl variable
API_URL,
});
But global variable aside if just want to get rid of the component and module import error, then you can simply set aliases for those in your .babelrc file. This way, you do not need to write '../../..something', you can just write 'something'.
{
"presets": ["react", "es2015", "stage-0"],
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"src": "/",
"components": "/components",
"actions": "/actions",
"containers": "/containers",
"images": "/images",
"reducers": "/reducers",
"styles": "/styles",
"utils": "/utils",
}
}]
]
}}
This is a sample .babelrc file with alias for components and other folders. Now from any where in the app if I write import { Something } from 'components/Something', my app will know where to find it. No need to write '../../../components/Something'
Comments
You can try this:
Parent.js
var myVar = {}
class MyComponent extends Component {
...
...
myVar = new Object();
...
...
render() {
return <div>
\\ children
<MyLeftBranch myVar={myVar} />
<MyRightBranch myVar={myVar} />
</div>
}
}
export default MyComponent;
child.js
class Child extends Component {
{ myVar } = this.props;
\\use myVar
}
ProvidePluginsounds like a good fit for defining a bunch of globals. webpack.js.org/plugins/provide-pluginexternalswebpack.js.org/configuration/externals