Cannot import react, Uncaught SyntaxError, Unexpected Identifier - javascript

I have a following problem. I setted up a React in my ASP.NET Core application as always, but now I have one irritating problem and I don't know how to fix it.
When I try to import react from 'react', nothing import. In Chrome Developer Tools I see a red underline under the sentene: "import React from 'react';".
I tried to change babel presets to another, change a webpack.config.js file but nothing works. Maybe you will have an idea, where is a bug? Here is my files:
.babelrc
{
"presets":["env", "react"]
}
package.json
{
"name": "MyApp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.10",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"node-sass": "^4.7.2",
"prop-types": "^15.6.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"sass-loader": "^6.0.7",
"style-loader": "^0.20.3",
"webpack": "^4.1.1",
"webpack-dev-server": "^3.1.1"
},
"dependencies": {}
}
webpack.config.js
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
devtool: 'source-map',
entry: './ClientApp/index.js',
output: {
publicPath: "/js/",
path: path.join(__dirname, "wwwroot", "js"),
filename: "index-bundle.js"
},
devServer: {
contentBase: "./dist"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|eot|ttf)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 50000,
name: 'assets/[name]_[hash].[ext]'
}
}
]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'sass-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin("./bundle.css")
]
}
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './Shared/styles/styles.scss';
import SignIn from './Sign/Shared/Components/Sign'
class App extends React.Component{
constructor(props){
super(props);
this.state = {
}
}
render(){
<div>
<SignIn />
</div>
}
}
ReactDOM.render(<App/>, document.getElementById('App'))
I will be very glad for your help.

import is a es2015 feature and I see no es2015 preset in .babelrc. See: https://www.npmjs.com/package/babel-preset-es2015

Add presets into babel-loader.
Change webpack.config.js in this way.
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use : {
loader : 'babel-loader',
options : {
presets : ['env', 'react'],
}
}
},

Try this : transform-es2015-modules-amd , This plugin transforms ES2015 modules to Asynchronous Module Definition (AMD). in .babelrc file
{
presets: ["env", "react"],
plugins: ["transform-es2015-modules-amd"]
}
more at transform-es2015-modules-amd

This can also occur if you run:
node index.js
instead of
npm start
See also: npm start vs node app.js

Related

bootstrap.css className is not effecting the styling of the website

I am trying to use bootstrap.css to go through a tutorial on react but for some reason the styling is not being updated, I feel like this is probably an issue with my webpack.config but I have tried numerous fixes with nothing working, here is my current config:
const path = require('path')
module.exports = {
devServer: {
contentBase: path.resolve(__dirname, './public'),
historyApiFallback: true,
},
entry: path.resolve(__dirname, './src/index.js'),
resolve: {
extensions: ['*', '.js', '.jsx'],
},
module: {
rules: [
{
test: /\.jsx?$/,
use: [
{
loader: 'babel-loader',
},
],
},
{
test: /\.(scss)$/,
use: [
{
loader: 'style-loader',
loader: 'css-loader',
loader: 'saas-loader',
loader: 'postcss-loader',
options: {
plugins: function () {
return [require('precss'), require('autoprefixer')]
},
modules: true,
},
},
],
},
{
test: /\.(css)$/,
use: [
{
loader: 'style-loader',
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
],
},
output: {
filename: 'bundle.js',
},
}
and also my package.json
{
"name": "trend-dot-com",
"version": "1.0.0",
"main": "index.js",
"license": "TBA",
"devDependencies": {
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2",
"#babel/preset-react": "^7.10.1",
"babel-loader": "^8.1.0",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"#babel/plugin-proposal-class-properties": "^7.10.1",
"#babel/plugin-syntax-class-properties": "^7.10.1",
"bootstrap": "^4.5.0",
"css-loader": "^3.5.3",
"jquery": "^3.5.1",
"postcss-loader": "^3.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"sass-loader": "^8.0.2",
"style-loader": "^1.2.1"
},
"scripts": {
"start": "webpack-dev-server --progress"
}
}
and finally my js code
import React, {Component} from 'react'
class Counter extends Component {
state = {
count: 1,
}
render() {
return (
<div id="test">
<span className="badge badge-primary m-2">{this.formatCount()}</span>
<button className="">Increment</button>
</div>
)
}
formatCount() {
const {count} = this.state
return count === 0 ? 'Zero' : count
}
}
export default Counter
Ive made sure to import the bootstrap.css in my index.js as well. Any help would be appreciated.
Edit: Here is my index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {render} from 'react-dom'
import 'bootstrap/dist/css/bootstrap.min.css'
import App from './components/app.jsx'
ReactDOM.render(<App />, document.getElementById('app'))
You have not imported it :)
You have to install it with npm or another module and import him :)
import 'bootstrap/dist/css/bootstrap.min.css'

Webpack (Module Build faild)

My error is :
"ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: D:/cource/React project/webpacktutorial/src/index.js: Unexpected token (7:16)"
I don't know why this error occurs every time I do so may thing for webpack,
I use CSS loader, babel loader or many loaders, but this thing is still not solved.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister();
webpack.config.js
const path = require( 'path');
module.exports = {
mode: 'none',
entry: path.join(__dirname, '/src/index.js'),
output: {
filename: 'App.js',
path: path.join(__dirname, '/dist')},
module:{
rules:[{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
}]
}
}
package.json
{
"name": "webpacktutorial",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
"scripts": {
"start": "webpack-dev-server",
"build": "webpack --mode production",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"babel-core": "6.26.3",
"babel-loader": "7.1.5",
"babel-preset-env": "1.7.0",
"babel-preset-react": "6.24.1",
"html-webpack-plugin": "3.2.0",
"react-hot-loader": "^4.11.1",
"webpack": "4.16.2",
"webpack-cli": "3.1.0",
"webpack-dev-server": "3.1.5"
}
}
App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Try to change Your module section with this, this is more stable option in my opinion:
const path = require( 'path');
module.exports = {
mode: 'none',
entry: path.join(__dirname, '/src/index.js'),
output: {
filename: 'App.js',
path: path.join(__dirname, '/dist')},
module:{
loaders:[{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}]
}
}
You can try my webpack config
module.exports = {
module: {
rules: [{
test: /\.scss$/,
use: [
'style-loader',
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
minimize: true,
sourceMap: true
}
},
{
loader: "sass-loader"
}
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: ["babel-loader", "eslint-loader"]
},
{
test: /\.(jpe?g|png|gif)$/i,
loader: "file-loader"
},
{
test: /\.(woff|ttf|otf|eot|woff2|svg)$/i,
loader: "file-loader"
}
]
}
};
Full config can be view here
My babel.rc
{
"presets": ["es2015", "react"],
"plugins": [
"transform-es2015-destructuring",
"transform-object-rest-spread",
["transform-class-properties", { "spec": true }]
]
}
My package.json dependency
"babel-cli": "6.26.0",
"babel-core": "6.26.3",
"babel-eslint": "8.2.6",
"babel-loader": "7.1.5",
"babel-plugin-transform-class-properties": "6.24.1",
"babel-plugin-transform-es2015-destructuring": "6.23.0",
"babel-plugin-transform-object-rest-spread": "6.26.0",
"babel-preset-es2015": "6.24.1",
"babel-preset-react": "6.24.1",
"babel-preset-stage-0": "6.24.1"
Source code
I was able to replicate your exact error after creating my own repository using your package.json. I was able to fix the error:
"ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: D:/cource/React project/webpacktutorial/src/index.js: Unexpected token (7:16)"
by adding my own .babelrc at the root of my directory. My .babelrc looks like this:
{
"presets": ["env", "react"]
}
After, I received an error regarding css-loader. To solve this, I did:
npm i -D style-loader css-loader
to get the packages and added another rule to webpack.config.js:
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]

Webpack - MiniCssExtractPlugin doesn't extract file

I've created webpack config to my VueJS project. I want to separate styles from javascript code. I've used mini-css-extract-plugin but finally I receive only bundle.js file. What's wrong with this config and where is a mistake? Is there any missing loader. My config is below:
import path from 'path';
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import VueLoaderPlugin from 'vue-loader/lib/plugin';
import UglifyJsPlugin from 'uglifyjs-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
const devMode = process.env.NODE_ENV !== 'production';
const prodPlugins = [
new UglifyJsPlugin(),
new MiniCssExtractPlugin({
filename: "css/style.css"
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.optimize\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorOptions: { discardComments: { removeAll: true } },
canPrint: true
})
];
const basicPlugins = [
new CleanWebpackPlugin('dist'),
new VueLoaderPlugin()
];
const config = {
entry: {
bundle: './src/main.js'
},
output: {
filename: 'js/[name].js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
{
test: /\.css$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
'css-loader'
]
},
{ test: /\.(scss|sass)$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
js: 'babel-loader',
}
}
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
plugins: !process.env.NODE_ENV || !devMode ? basicPlugins : basicPlugins.concat(prodPlugins)
};
module.exports = config;
My file package.json
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"watch": "webpack --watch --mode development --hot",
"dev": "webpack-dev-server --mode development --progress --hot --open",
"build": "webpack --mode production --progress"
},
"author": "",
"license": "MIT",
"devDependencies": {
"autoprefixer-loader": "^3.2.0",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-register": "^6.26.0",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"cssnano": "^3.10.0",
"eslint": "^4.19.1",
"eslint-watch": "^3.1.4",
"mini-css-extract-plugin": "^0.4.0",
"node-sass": "^4.9.0",
"optimize-css-assets-webpack-plugin": "^4.0.1",
"sass-loader": "^7.0.1",
"sass-resources-loader": "^1.3.3",
"style-loader": "^0.21.0",
"uglifyjs-webpack-plugin": "^1.2.5",
"vue-loader": "^15.0.10",
"vue-style-loader": "^4.1.0",
"vue-template-compiler": "^2.5.16",
"webpack": "^4.8.3",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4"
},
"dependencies": {
"axios": "^0.18.0",
"material-design-icons": "^3.0.1",
"vue": "^2.5.16",
"vue-router": "^3.0.1",
"vuetify": "^1.0.17"
}
}
Note that any imported file is subject to tree shaking. This means if you use something like css-loader in your project and import a CSS file, it needs to be added to the side effect list so it will not be unintentionally dropped in production mode.
Blockquote
in your package.json, add:
"sideEffects": [
'.scss'
]
In Webpack 4, you can add "sideEffects: true" to the loader to prevent the compiler from dropping the CSS file output by MiniCssExtractPlugin.loader (See Webpack Tree Shaking Guide). This works with Angular + TypeScript (using "module:" "ES2015" in tsconfig). I imagine it would work for your set up as well.
{
test: /\.scss$/,
include: [
helpers.root('src', 'assets')
],
sideEffects: true,
use: [
MiniCssExtractPlugin.loader,
{loader: 'css-loader'},
{loader: 'resolve-url-loader'}, // Angular only
{loader: 'sass-loader'},
]
},
Check that you have set the NODE_ENV environment variable.
In your config the extracting of css to separate files (MiniCssExtractPlugin) will only occur when building for production, in other words, when NODE_ENV is set to 'production'. When building for development style-loader is being used which will inject the css within a tag.

ReactJS loading in other application returns Module parse failed ERROR in index.js

I'm using a pretty new JS dev environment (here for details) and according to this documentation React is pretty easy to implement into other JS frameworks.
In my index.js file which is at the root of my directory, I have the following code:
import React, { Component } from "react";
import ReactDOM from "react-dom";
function Button() {
return <button id="btn">Say Hello</button>;
}
ReactDOM.render(
<Button />,
document.getElementById('container'),
function() {
$('#btn').click(function() {
alert('Hello!');
});
}
);
and when i go to run fly server I get the following error:
ERROR in ./index.js Module parse failed: Unexpected token (8:9) You
may need an appropriate loader to handle this file type. | | function
Button() { | return Say Hello; | } |
Here is my package.json file:
{
"name": "fly-example",
"version": "1.0.0",
"description": "fly example app",
"main": "index.js",
"dependencies": {
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"css-loader": "^0.28.11",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"style-loader": "^0.21.0",
"webpack": "^4.6.0",
"webpack-cli": "^2.0.14",
"webpack-dev-server": "^3.1.3"
},
"scripts": {
"test": "mocha"
},
"repository": {
"type": "git",
"url": "none"
},
"keywords": [
"fly",
"app"
],
and my webpack.config:
const path = require("path");
const webpack = require("webpack");
const bundlePath = path.resolve(__dirname, "dist/");
module.exports = {
entry: "./index.js",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: { presets: ['env'] }
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
resolve: { extensions: ['*', '.js', '.jsx'] },
output: {
publicPath: bundlePath,
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname,'public'),
port: 3000,
publicPath: "http://localhost:3000/dist"
},
plugins: [ new webpack.HotModuleReplacementPlugin() ]
};
.babelrc file:
{
"presets": ["env", "react"]
}
Still fairly new to React, but I love building apps in it, but I really want to learn how to integrate it into other JS frameworks so I can use it more broadly.
Is there something I'm missing in the package.json file or the webpack.config? I have done quite a bit of looking around but haven't found much.
Thanks for your help in advance!
Try specifying babel-loader under use.loader. See below:
const path = require("path");
const webpack = require("webpack");
const bundlePath = path.resolve(__dirname, "dist/");
module.exports = {
entry: "./index.js",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
}
options: { presets: ['env'] }
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
},
resolve: { extensions: ['*', '.js', '.jsx'] },
output: {
publicPath: bundlePath,
filename: "bundle.js"
},
devServer: {
contentBase: path.join(__dirname,'public'),
port: 3000,
publicPath: "http://localhost:3000/dist"
},
plugins: [ new webpack.HotModuleReplacementPlugin() ]
};
Instead of writing the webpack configuration by yourself, I'd recommend using create-react-app, it is simpler. Also make sure you import jquery.
Try and let me know if this works !

ReactDOM.render() Not Working - You may need an appropriate loader to handle this file type

I have been following a course on Udemy.com and have run into a problem that I am unable to fix. I have webpack installed as well as babel and followed the instructions through a second time to double check that I didn't make a mistake.
When trying to run this code in my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<div>HELLO!</div>, document.getElementById('root')
);
I get the Error:
ERROR in ./app/index.js
Module parse failed: /Users/Kyle/Documents/React Native Workspace/es6Project/app/index.js Unexpected token (5:2)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
| <div>HELLO!</div>, document.getElementById('root')
| );
|
# multi (webpack)-dev-server/client?http://localhost:3000 ./app/index.js
Here is my package.json:
{
"name": "es6Project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server"
},
"babel": {
"presets": [
"es2015",
"es2016",
"es2017",
"react"
]
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2016": "^6.24.1",
"babel-preset-es2017": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.0.0",
"react-bootstrap": "^0.31.3",
"react-dom": "^16.0.0",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.9.1"
}
}
Here is my webpack.config.js:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: ['./app/index.js'],
output: {
path: __dirname + '.build',
filename: 'bundle.js'
},
plugins: [
new webpack.LoaderOptionsPlugin({
options: {
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.jsx?$/,
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
}
}
})
],
devServer: {
port: 3000,
contentBase: './build',
inline: true
}
}
Your webpack configuration is wrong. The error you are getting is regarding JSX, being unable to be parsed due to misconfiguration.
Also since you are creating a new project, why are you using a plugin that its purpose is to migrate from webpack 1.x versions to 2.x ?
If you use webpack version 2.x modify module.exports to contain:
module: {
rules: [
{
test: /\.(js)$/,
use:[{
loader: 'babel-loader',
query: {
compact: false,
presets: [["es2015", {"modules": false, "loose" : true}], 'react']
}
}]
}
]
}
check your application where you have rendering your app.
check you html file. the code which you have return it is good.
please go thorugh reactjs tutorial point
https://www.tutorialspoint.com/reactjs/reactjs_overview.htm

Categories

Resources