I'm trying to learn React with node.js following an online tutorial https://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm. When I run the Main.js I got the following error:(function (exports, require, module, __filename, __dirname) { import React from 'react';
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:76:16)
....
Here's the main.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
And the app.jsx:
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
Webpack.config.js:
var config = {
entry: './main.js',
output: {
path:'./',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.exports = config;
I searched for answers. Some said to use 'require' rather than import. I didn't quite understand how to use it or whether it's related to this issue. Can someone please help to explain? Many thanks in advance!
Related
There was a problem with importing react component with JXS. Components are imported from library (used like a SDK).
/sdk/dist/js/app.js
import React, { Component } from 'react';
export default class Test extends Component {
render() {
return <div>Hello</div>;
}
}
There is a project where this SDK is used, there is webpack / babel that already does a build, the file with import of this component looks like this:
app/js/index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Test from 'sdk/dist/js/App';
Result:
BUT!
Everything will work if:
We remove JSX from this component
app/js/index.js
import React, { Component } from 'react';
export default class Test extends Component {
render() {
return React.createElement(
"div",
null,
"Hello"
);
}
}
Remove import and insert component directly.
app/js/index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Test extends Component {
render() {
return <div>Hello</div>;
}
}
The problem is that it needs to work through import. I suggest that the problem is that the webpack does not transpose the imported file - and reads it as is ...
webpack:
{
entry: './app/js/index.js',
output: {
path: resolve(__dirname, plConfig.paths.public.root),
filename: "[name].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: [
{
loader: "babel-loader",
options: {
cacheDirectory: true
}
}
]
}
]
}
.babelrc:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
You'll need a babel plugin to transform jsx...
#babel/plugin-transform-react-jsx
Install
npm i -D #babel/plugin-transform-react-jsx
Use in .babelrc
{
presets: [ ... ],
plugins: [ "#babel/plugin-transform-react-jsx", ...other plugins ]
}
EDIT:
You also need to add a babel rule for jsx...
In your webpack module rules...
Change test: /\.js$/ to test: /\.jsx?$/
I am not sure if react router is not working correctly or if I am missing something.
I have something like this
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import { configure } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import {syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router'
import AppContainer from './components/App';
const browserHistory = createBrowserHistory();
import stores from '../src/stores/Stores';
const history = syncHistoryWithStore(browserHistory, stores.routingStore);
configure({ enforceActions: true});
ReactDOM.render(
<Provider {... stores}>
<Router history={history}>
<AppContainer />
</Router>
</Provider>,
document.getElementById('app')
);
Then in my AppContainer I have this
import { withRouter, Route, Link } from "react-router-dom";
<Route path="/company-details/company/:companyId/employee/:employeeId" component={CompanyComponent} />
and
<Link to="/company-details/company/76/employee/77"></Link>
now when I click on the link, it goes to the right page and I got access to the parameters.
but say if I did ctrl + click to make a new tab while clicking on the link or refreshing the page.
I get
GET http://localhost:8080/company-details/company/76/employee/index_bundle.js 404 (Not Found)
Refused to execute script from 'http://localhost:8080/company-details/company/76/employee/index_bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
I have these packages installed
"react-router-dom": "^4.2.2"
"mobx-react-router": "^4.0.4",
Edit
my webpack.config
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: ["babel-polyfill", "./src/index.js"],
output: {
path: path.join(__dirname, "/dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /(\.css|\.scss|\.sass)$/,
use: [
{
loader: "style-loader" // creates style nodes from JS strings
},
{
loader: "css-loader" // translates CSS into CommonJS
},
{
loader: "sass-loader" // compiles Sass to CSS
}
]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: "./src/index.html"
})
],
devServer: {
historyApiFallback: true
}
};
Inside index.html you should link your script file like following:
<script type="text/javascript" src="./index_bundle.js"></script>
I am building a simple form with react, using webpack. I'm new to webpack and react, so there might be an obvious solution, but I just can't figure it out.
My code structure (simplified):
root:
- server.js
- webpack.config.js
- src:
-- App.js
-- index.js
- public:
-- index.html
-- bundle.js
In my app.js is only one Component. I have excluded the ReactDOM.render method into a file index.js. Since i've done that it doesn't work anymore. Before it worked just fine.
The App isn't rendered into my index.html anymore. I guess webpack compiles only my app.js file and ignores my index.js. But I can't know for sure.
When I include the index.js into my App.js everything works just fine.
// /src/App.js
import React, {Component} from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
form: 'firmenkontakt'
}
};
render() {
return (
<div className={this.state}>
<form method="post" id={this.state}>
...
</form>
</div>
)
}
}
export default App;
The rendering-file looks as follow:
// /src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('app'));
registerServiceWorker();
I wonder if anything is wrong about my webpack.config.js
// /webpack.config.js
let path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/App.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'public')
},
watch: true,
module: {
loaders: [
{
test:/\.js$/,
exclude: /node_module/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}
]
}
}
Your entry file should be src/index.js' and it must importApp.js`
I just simply want to export and import a child component into my rot-directory (App.js) and render it out in the browser, but I get this error message in terminal "Module not found: Error: Cannot resolve 'file' or 'directory'". I don't understand what I typed wrong or why I cannot import my child to my App.js.
Have tried to solve this problem but with no results. I've been testing this in my "App.js" to get a more explicit name but not working:
import { ContactsList } from './ContactsList';
I've also tried typing this in my "ContactsList.js" but with no result:
export default class ContactsList extends React.Component {}
I'am a beginner so excuse me for my knowledge but I really want to learn this and the power of react. Please help me for better understanding!
--------App.js---------
import React from 'react';
import ReactDOM from 'react-dom';
import ContactsList from './ContactsList';
class App extends React.Component {
render() {
return (
<div>
<h1>Contacts List</h1>
<ContactsList />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
--------ContactsList.js---------
import React from 'react';
import ReactDOM from 'react-dom';
class ContactsList extends React.Component {
render() {
return (
<ul>
<li>Joe 555 555 5555</li>
<li>Marv 555 555 5555</li>
</ul>
)
}
}
export default ContactsList;
--------webpack.config.js---------
module.exports = {
entry: './src/App.js',
output: {
path: __dirname,
filename: 'app.js'
},
module: {
loaders: [{
test:/\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
}
};
In your ContactsList.js file, use a <div> to wrap the <ul>
Also in your webpack config file. Can you try to use loader : "babel-loader" instead of loader: 'babel'(Don't forget to install the babel-loader package)
Also remove the query part and try to create a separate .babelrc file with the following settings:
{
"presets" : [
"react",
"es2015"
]
}
Hope this can solve your problem
According to es6 module mechanism the default module should be
imported without {}
import ContactsList from './ContactsList';
and export like
export default class ContactsList extends React.Component {}
But I guess you are trying babel on .jsx extension however it seams
you are using ContactsList.js
Just change the to .jsx to .js in
--webpack.config.js
module.exports = {
entry: './src/App.js',
output: {
path: __dirname,
filename: 'app.js'
},
module: {
loaders: [{
test:/\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}]
}
};
Hope it works
You need to do some changes on webpack.config.js file. first replace
test:/\.jsx?$/,
with
test: /\.(js|jsx)$/,
Secondly import modules as follows
import ContactsList from 'path-of-the-file';
But you need to provide the actual path. to get the path correct there are many plugins available depending on the text editors we use. i am using https://github.com/sagold/FuzzyFilePath
I am using webpack and babel. I have a file like this:
import React from 'react';
import ReactRedux from 'react-redux';
var Layout = React.createClass({
render(){
return (<div>Markup</div>);
}
});
function mapStateToProps(state, action) {
return state;
}
export default ReactRedux.connect(mapStateToProps)(Layout);
For some reason when I run webpack, after compiling, it runs with this error: Cannot read property 'connect' of undefined. Not sure why it would fail at getting ReactRedux object. My webpack config is like this:
var compiler = webpack({
entry: "./dist/runner.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel', // 'babel-loader' is also a legal name to reference
query: {
presets: ['es2015', 'react']
}
}
]
},
devtool: 'source-map',
output: {
filename: "public/dist/bundle.js"
}
});
This is because the react-redux package doesn't have a default export on the module. You can access the connect function manually like:
import { connect } from 'react-redux';
...
export default connect(mapStateToProps)(Layout);