Webpack doesn't understand React's syntax - reactjs

I am learning both React and Webpack. Now I have written a component that displays a name ;-)
const app = document.getElementById('app');
class World extends React.Component {
constructor(props) {
super(props);
this.name = 'Tomek';
this.callByName = this.callByName.bind(this); /* Or bind directly when calling */
}
callByName() {
alert(this.name);
}
render() {
return (
<div>
<h2>Hello, {this.name}</h2>
<button onClick={this.callByName}>Alert</button>
</div>
)
}
}
ReactDOM.render(<World />, app);
I import it with React and ReactDOM:
import React from 'react';
import ReactDOM from 'react-dom';
import './components/posts/index.js';
I use Webpack to process my JS:
module.exports = {
entry: [
'./_babel/index.js'
],
output: {
path: __dirname + '/_js',
filename: 'index.js'
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
]
}
};
Unfortunately, when I run webpack, I get
ERROR in ./_babel/components/posts/index.js
Module build failed: SyntaxError: /Users/tomek/Sites/wordpress/wp-content/themes/Devoid/_babel/components/posts/index.js: Unexpected token (17:6)
render() {
return (
<div>
<h2>Hello, {this.name}</h2>
<button onClick={this.callByName}>Alert</button>
</div>
Propably I just forgot something, but I can't seem to find what.

You need to add the react loader to your webpack.config.js. I also suggest adding ES2015 loader. Try this:
module.exports = {
entry: [
'./_babel/index.js'
],
output: {
path: __dirname + '/_js',
filename: 'index.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {presets: ['es2015']}
},
{
test: /\.jsx$/,
loader:'babel-loader',
query: {presets: ['es2015', 'react']}
}
]
}
};

Related

Module not found: Error: Can't resolve ' ' when trying to run webpack

I get this error when I try to run webpack but it doesnt really show me what module it cant find. I get this error 4 times in different files. I am starting webpack via commandline with "webpack". I dont see the point
ERROR in ./src/index.js
Module not found: Error: Can't resolve '' in 'C:\Users\topal\IdeaProjects\cts-abwesendheitstool\cts-abwesendheit-fe'
# ./src/index.js 4:0-21
This is my code in index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App/>,
document.getElementById('root')
);
my webpack config
const webpack = require('webpack');
const path = require('path');
module.exports = {
entry: path.resolve(__dirname, './src/index.js'),
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [[
'#babel/preset-env', {
targets: {
esmodules: true
}
}],
'#babel/preset-react']
}
}
},
{
test: /\.css$/,
loader: 'style-loader!css-loader!',
},
{
test: path.join(__dirname, '.'),
exclude: /(node_modules)/,
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env',
'#babel/react', {
'plugins': ['#babel/plugin-proposal-class-properties']
}]
}
},
{test: /\.json$/, loader: 'json-loader'}
],
},
resolve: {
extensions: ['*', '.js', '.jsx','.ts', '.tsx'],
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
plugins: [new webpack.HotModuleReplacementPlugin()],
devServer: {
contentBase: path.resolve(__dirname, './dist'),
hot: true,
},
};
In a different file:
import "./App.css";
import Datagrid from "./pages/Datagrid"
import {React, useEffect, useState} from "react";
import * as config from "./config/config";
import DaterangePicker from "./components/DaterangePicker";
function App() {
const [data,setData]= useState([]);
useEffect(()=>{
const requestOptions = {
method: 'GET'
};
fetch(config.SERVER_URL + `/caldav/getEvents/${config.CALENDAR}`, requestOptions)
.then((response) => response.json())
.then(data => setData(data))
.catch(error => console.log(error));
},[data.length]);
return (
<div className="App">
<header className="App-header">
Abwesendheitscheckliste
</header>
<DaterangePicker/>
<Datagrid rows={data}></Datagrid>
</div>
);
}
export default App;
I get the same error:
ERROR in ./src/App.js
Module not found: Error: Can't resolve '' in 'C:\Users\topal\IdeaProjects\cts-abwesendheitstool\cts-abwesendheit-fe'
# ./src/App.js 2:0-19
# ./src/index.js
Can you try something like this in webpack
use: ["style-loader", "css-loader"],

Module not found: Error: Can't resolve './component/Hello'

I´m trying to import a simple Component but the webpack seems to cant find it. The route is good and the "resolve" in the webpack config is great too, therefore I cant understand where is the issue.
Give it at look please.
By the way, its a Sails/React environment.
ERROR in ./assets/src/component/Hello.jsx 6:12
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
Hello.jsx:
import React from 'react'
class Hello extends React.Component {
render() {
return(
<div> // Err supposed to be here (line6)
Hello World!
</div>
)
}
}
export default Hello;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component/Hello'
const App = () => {
return (
<div>
Simple Sails-React stater
<Hello/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
.babelrc:
{
"presets": ["#babel/env", "#babel/react"]
}
webpack config file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
entry: './assets/src/index.js'
},
output: {
path: __dirname + '/.tmp/public',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
template: 'assets/src/index.html'
})
]
};
the structure is like this:
-src
--component
----Hello.jsx
--index.js
--index.html
Could you try change extension to Hello.js or change bable-loader test to
test: /\.(js|jsx)$/,

webpack 3.8.1 facebook react import node module css not working

I am using Facebook react with Webpack and I import node module CSS in my component. It's not working.
webpack.config.js
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve("dist"),
filename: "index_bundle.js"
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
query: {
presets: ["react", "es2015", "stage-0"],
plugins: ["transform-class-properties"]
}
},
{
test: /\.css?$/,
loaders: ExtractTextPlugin.extract(
"style-loader!css-loader?modules=true&localIdentName=[name]_[local]_[hash:base64:5]"
)
}
]
},
plugins: [new ExtractTextPlugin("./public/styles.css")]
};
React component file
I import react-times css file
import React from "react";
import TimePicker from "react-times";
import "react-times/css/material/default.css";
export default class Book extends React.Component {
render() {
return (
<TimePicker />
);
}
}
you can try
// module
{
test : /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader']
})
}
// plugins
new ExtractTextPlugin("styles.css")

React-Date "SingleDatePicker" not working as expected?

I am using react-dates and trying to implement singledatepicker. All the functionality is working but I dont know why all the default styles are gone. I am also using babel "transform-class-properties"
import React from 'react';
import moment from 'moment'
import 'react-dates/initialize';
import {SingleDatePicker} from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';
const now= moment();
export default class ExpenseForm extends React.Component{
state={
description:'',
note:'',
amount:'',
createdAt:moment(),
calendarFocused:false
}
onDateChange = (createdAt)=>{
this.setState(()=>({createdAt}));
}
onFocusChange =({focused})=>{
this.setState(()=>({calendarFocused:focused}))
}
render(){
return(
<div>
<h3>ExpenseForm</h3>
<form>
<SingleDatePicker
date={this.state.createdAt}
onDateChange={this.onDateChange}
focused={this.state.calendarFocused}
onFocusChange={this.onFocusChange}
/>
</form>
</div>
)
}
}
Here is my Webpack config file and it is loaded with css-loader
const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},{
test: /\.s?css$/,
use:['style-loader','css-loader','sass-loader']
}
]
},
devtool:'cheap-module-eval-source-map',
devServer:{
contentBase:path.resolve(__dirname, 'public'),
historyApiFallback:true
}
};
I had exact the same problem when integration react-dates into my project, and I believe the root cause is that the css module in your project also compile the css of react-dates which leads to missing of the style. To solve this problem, you could modify the rule in your module like:
...your original css module rule
exclude: [
/node_modules/
]
after applying this rule, you might encounter another issue which is that these css files can't be properly handled due to being excluded, you should then add another css module to handle those css file that you don't want to mess with, for example:
exports.vendorCss = {
test: /\.(css|scss|sass)$/,
include: [/node_modules/],
loaders: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
};
and there you have it!! Hope this can help!

How to render a foo.md markdown file in react?

I have several .md files (containing long texts) and I want to render them through react. I tried to use markedown-it but the loader returns an error. Here is the webpack.config.js file:
var path = require('path');
var webpack = require('webpack');
var subscript = require('markdown-it');
var superscript = require('markdown-it');
module.exports = {
entry: ['./src/first.jsx'],
devtool: 'cheap-module-eval-source-map',
output: { path: __dirname+"/app", filename: 'bundle.js' },
module: {
loaders: [
{ test: /\.jsx?$/,
loader: 'babel-loader',
query: { presets: ['es2015', 'react'] },
include: path.join(__dirname, 'src')
},
{ test: /\.md/,
loader: 'markdown-it'
}
]
},
'markdown-it': {
preset: 'default',
typographer: true,
use: [subscript, superscript]
}
};
Is there something wrong with that file? How else I can add my *.md files to react?
After reading http://www.shoutinginfrench.com/today-i-made-react-load-markdown/ I tried to use markdown-loader. Following that, I added this to webpack.config file:
{ test: /\.md$/,
loader: "html!markdown"
}
which worked with no problem. Then I tried to add the markdown file to the react component as follow:
import React from 'react';
import { Link } from 'react-router'
import markdownFile from './test-file.md';
export const Test = React.createClass({
rawMarkup(){
return { __html: markdownFile };
},
render() {
return (
<div className="something">
<div className="row">
<div className="col-10">
<div dangerouslySetInnerHtml={this.rawMarkup()} />
</div>
</div>
</div>
);
}
});
But I'm getting the following error:
ERROR in ./src/components/tst.jsx
Module not found: Error: Cannot resolve module 'html' in /Users/..../src/components
# ./src/components/tst.jsx 14:15-39
How can I fix it?!
add { test: /\.md$/, loader: "html!markdown" },{ test: /\.json$/, loader: "json" } to your webpack.config.js .
npm install react-markdown --save-dev

Resources