I'm using Webpack to bundle my ReactJS application.
helloworld.js
import React from 'react';
export default class HelloWorld extends React.Component {
render() {
return <h2>Hello {this.props.name}!</h2>;
}
}
index.js
import ReactDOM from 'react-dom';
import HelloWorld from './helloworld';
ReactDOM.render(<HelloWorld name="World" />,
document.getElementById('container'));
webpack.config.js
module.exports = {
entry: './index.js',
output: 'bundle.js',
module: {
loaders: [
{
test: /(\.js|\.jsx)/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
}
};
When I run webpack-dev-server --progress --colors I'm getting an error in the browser "React is not defined" but if I import React directly in the index.js then the error not comes. Why Webpack is not including React in the bundle if it is referenced in the helloworld.js file?
Well webpack only tries to bundle up the individual modules by reading the dependencies in it and resolving them to render a particular element. Now while bundling
ReactDOM.render(<HelloWorld name="World" />,
document.getElementById('container'));
ReactDOM tries to execute React.createElement(_Helloworld2.default, { name: 'World' }), document.getElementById('app') function which requires React as a dependency that is not present in your index.js file so it gives an error and solve the issue when you import React in your index.js file. I hope I was able to explain and my answer helps you.
You are missing import React from 'react'; statement.
You will need it every time You write some JSX in a file, because it is transformed into React.createElement(..) function calls.
Related
I am trying to dynamically import react component library from API. The js file is fetched succesfully. The babel transpilation has happened successfully too. If I dynamically import the Dummy.js file from localhost like import Dummy from './components/js/Dummy.js', it works. However API import fails with below error. The same error occurs with react lazy too. I basically want to dynamically load the lib and publish events to it. I am newbie to react and front-end development. Please excuse if this is too silly!.
Error resolving module specifier: react
My App.js
import React, { lazy, Suspense } from 'react';
import './App.css';
import ErrorBoundary from './ErrorBoundary';
class App extends React.Component {
render(){
const loader = () => import( /*webpackIgnore: true*/ `https://example.com/Dummy.js`);
const Dummy = ReactDynamicImport({ loader });
const LoadingMessage = () => (
"I'm loading..."
)
return (
<div className="App">
<h1>Simplewidget</h1>
<div id="simplewidget">
<ErrorBoundary>
<Suspense fallback={LoadingMessage}>
<Dummy />
</Suspense>
</ErrorBoundary>
</div>
</div>
);
}
}
export default App;
rollup.config.js, After multiple attempts I arrived at below configuration https://github.com/jaebradley/example-rollup-react-component-npm-package/blob/master/rollup.config.js
// node-resolve will resolve all the node dependencies
import resolve from '#rollup/plugin-node-resolve';
import babel from 'rollup-plugin-babel';
import commonjs from '#rollup/plugin-commonjs';
import filesize from 'rollup-plugin-filesize';
import localResolve from 'rollup-plugin-local-resolve';
export default {
input: 'src/components/js/Dummy.js',
output: {
file: 'dist/Dummy.js',
format: 'es',
globals: {
react: 'React',
'react-dom': 'ReactDOM'
}
},
// All the used libs needs to be here
external: [
'react',
'react-dom'
],
plugins: [
babel({
exclude: 'node_modules/**',
}),
localResolve(),
resolve({
browser: true,
}),
commonjs(),
filesize()
]
}
Dummy.js. I verified in dist/dummy.js that babel transpilation happened correctly. I uploaded the transpiled version to my static hosting site.
import React from "react";
import ReactDOM from "react-dom";
class Dummy extends React.Component {
render() {
return (
<h1>Hello</h1>
);
}
}
export default Dummy;
I have different targets to build, start up my server, create rollup bundle, etc in same app. So, I am pretty confident my rollup doesn't interfere with running the app.
The rollup bundling configuration isn't correct. I was trying to create an es output with commonjs plugin while actually I required an esm module. The error on 'react' is because it is unresolved. Had to make it to use window.React while doing rollup bundle. Also, the App.js should be rolled up as esm bundle to make it dynamically import Dummy.js. In the HTML where app.js's bundle is included, I had to include react and react js umd scripts.
export default {
input: "./src/components/js/Dummy.js",
output: {
file: './dist/Dummy.js',
format: 'esm'
},
plugins: [
babel({
exclude: "node_modules/**"
}),
resolve(),
externalGlobals({
"react": "window.React",
"react-dom": "window.ReactDOM",
})
]
};
I'm trying to convert a working ReactJS application into TypeScript, and I've had some issues getting anything to work properly.
import React from "react";
import * as ReactDOM from "react-dom";
import Application from "./Application";
console.log(React); // undefined
ReactDOM.render(
<Application/>, window.document.getElementById("application-wrapper")
);
The console throws an error at <Application />
When I import react like this, react loads:
import * as React from "react";
However, I want to use the import statement using the default export, because I import React using this import syntax in all the existing components:
import React, {Component} from "react";
export default class Whatever extends Component<Props, State> {
...
}
My tsconfig.json file contains this line allowing synthetic defaults:
"allowSyntheticDefaultImports": true
My webpack.config.js file:
let path = require("path");
let config = {
entry: "./src/main.tsx",
output: {
path: path.resolve(__dirname, "build"),
filename: "bundle.js"
},
devtool: "source-map",
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx"]
},
module: {
loaders: [
{
test: /\.tsx?$/,
loader: "ts-loader",
exclude: /node_modules/
}
]
}
};
module.exports = config;
Not sure what I'm missing here....
Set "esModuleInterop": true instead.
In your typescript configuration i.e tsconfig.json "esModuleInterop": true and "allowSyntheticDefaultImports": true. this will allow you to import CommonJS modules in compliance with es6 modules spec.
Module resolution is a little complicated because Typescript does it different than Babel and Webpack. If you want to know more you can check this comment: https://github.com/Microsoft/TypeScript/issues/5565#issuecomment-155216760
Going back to your problem, allowSyntheticDefaultImports tells Typescript to allow default imports from modules with no default export but the emitted code doesn't change. Because of that, you need to move the responsibility of resolving modules to Webpack or Babel.
To achieve that set moduleResolution module to ES6es2015 in the Typescript config file.
The pipeline will look like this:
TS Code => (TypescriptCompiler) => JS Code with ES6 modules => (Webpack modules resolver) => JS Code
In my react js application,after webpack compilation it shows an error in console uncaught syntax error:Unexpected token import which refers to the line in bundle.js (output file) import React from 'react'; .
this is the referred line and its adjacent lines.
var replaceLocation = exports.replaceLocation = function replaceLocation(location, pathCoder, queryKey) {
return updateLocation(location, pathCoder, queryKey, function (path) {
if (getHashPath() !== path) replaceHashPath(path);
});
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
/***/ }),
/* 282 */
/***/ (function(module, exports) {
import React from 'react';
import WatchableStore from 'watchable-store';
import { CSSTransitionGroup } from 'react-transition-group';
import './animate.css';
import './styles.css';
i dont know whats happening,am new in react... thanks in advance
The error points to import keyword. ES6 modules don't work in browser environment, so you need to use babel (babel-loader for webpack) to compile ES6 unsupported code into ES5 code.
You need to set up .babelrc file with at least these presets:
{
"presets": ["es2015", "react"]
}
And then in webpack.config loaders:
{
test: /.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
Here is one of the articles on this topic. You can find more yourself.
I am trying webpack with React and Babel. I created a simple example:
components.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import { render } from 'react-dom'
class Hello extends React.Component {
render() {
return <h1>Hello</h1>
}
}
ReactDOM.render(<Hello/>, document.getElementById('test'));
export default Hello;
index.js:
import Hello from "components.jsx";
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webpack, React and Babel example</title>
</head>
<body>
<div> </div>
<div id="test"> </div>
<script src="bundle.js"> </script>
</body>
</html>
webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: './index.js',
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
}
};
I also installed all the necessary modules: babel-loader, babel-core babel-preset-es2015 babel-preset-react, react, react-dom.
However, when I typed "webpack" in this current folder, I always got error message:
ERROR in ./index.js Module not found: Error: Cannot resolve module
'components.jsx' in
It is such a simple example and I must make a huge dumb mistake. But I just cannot find it.
Thanks
Derek
When you try to import a module by name, it's expected to be found under node_modules. That's probably not where you want it to be though, so you should import it via (a relative) path instead.
import Hello from "./components.jsx";
If the index.js and components.jsx files share a folder, the above will work. If they don't then you need to change ./ to point to the correct location.
As I understood, index.js and components.jsx are located in the same folder, if it is true, path should be the following
import Hello from "./components.jsx";
I practice react
I met this error : Uncaught ReferenceError: ReactDOM is not defined
when type ReactDOM.unmountComponentAtNode(document.body) on chrome console
Please help me check the problem
I try the code on JSbin and works well,so I think it's webpack problem,but I have no idea .
And I notice there are many way write React.render part when I google ,what's the difference?? which one is correct??
React.render(<App name='Vipul' />,document.body);
ReactDOM.render(<App name='Vipul' />,document.body);
React.renderComponents(<App name='Vipul' />,document.body);
Here is my code:
main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
console.log('Start')
var App = React.createClass({
render: function(){
console.log('render');
return <h1 onClick={this.toggleState}>Hello</h1>
},
componentWillUnmount: function(){
//在console執行 ReactDOM.unmountComponentAtNode(document.body)
console.log('componentWillUnmount');
},
toggleState: function(){
this.setState({status: !this.state.status})
}
});
ReactDOM.render(<App name='Vipul' />,document.body);
webpack.config.js
var WebpackNotifierPlugin = require('webpack-notifier');
module.exports = {
entry: "./src/main.js",
output: {
filename: "./dist/bundle.js"
// filename: "./public/dist/bundle.js"
},
plugins: [
new WebpackNotifierPlugin()
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: "babel-loader",
query: {
presets: ['es2015', 'react']
}
}
]
},devtool: 'source-map'
};
ReactDOM available since 0.14.0, so
ReactDOM.render(<App name='Vipul' />,document.body);
should be fine. If you are using lower version of React then React.render
Secondly it is recommended not to render on document.body, rather create a div inside the body and render there.
I met this error : Uncaught ReferenceError: ReactDOM is not defined
when type ReactDOM.unmountComponentAtNode(document.body) on chrome console
when you use Webpack the React and ReactDOM will not be available globally. So, this code will only work inside the file/module where you have imported React & ReactDOM.
There is only one way to render React component in browser and it's this one:
ReactDOM.render(<App />, target);
All other are deprecated - renderComponent is renamed to render and moved from react package to react-dom package.
Also, do you need to call unmountComponentAtNode in your componentWillUnmount lifecycle method? In your particular case it does not make sense. React will unmount component for you - for free.
componentWillUnmount usually serves for clearing timeouts/intervals and/or canceling async operations (Promises, closing connections, ...);
Removing that call won't harm you, try it out.