babel jsx SyntaxError: Unexpected token - reactjs

I'm a learner of react and run into a bug that I don't know how to solve.
I first write the code on codepen, and it runs without problem. Here is the link to my codepen. After exporting it to the local machine, I setup the webpack to handle the compilation. And I receive the error of unexpected token.
After reading all the answers with this title, I still can't solve my bug.
I've updated my webpack cofig file according to the answers, re-installed the dependencies, used a couple of other react boilerplates(1, I currently use this one, but I've also tried some other react starter templates). After I remove the code that the console indicates, I've got another bug pointing to other place in the code.
Thanks in advance.
And here are my codes.
part of the webpack.config.js:
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015']
}
}
.babelrc:
{
"presets": ["es2015", "react"],
"env": {
"development": {
"presets": ["react-hmre"]
}
}
}
CommentList.js:
import React, { Component, PropTypes } from 'react'
import Comment from './Comment'
class CommentList extends Component {
render() {
const CommentNodes = this.props.data.map((comment)=>{
return (
<Comment author={comment.author} key={comment.id}>{comment.txt}<Comment/>
)
})
return (
<div className="commentList">
<h2>Comments:</h2>
{CommentNodes}
</div>
)
}
}
CommentList.propTypes = {
data: PropTypes.array.isRequired
}
export default CommentList
the error:
/Users/liulian/Documents/React-flux/react-boilerplate/src/components/commentBox/CommentList.js
22:9 error Parsing error: Unexpected token
Module build failed: SyntaxError: /Users/liulian/Documents/React-flux/react-boilerplate/src/components/commentBox/CommentList.js: Unexpected token (22:8)
Points to lines of code below, beginning from line 21 to line 25:
CommentList.propTypes = {
data: PropTypes.array.isRequired
}
export default CommentList

Related

CSS Modules cannot be imported from within node_modules

I am using one library in my main project. The library code looks like this /node_modules/#myCompany/all_components/src/Footer/components/Navlink/index.js
import React from 'react';
import styles from './style.module.scss';
export const NavLinks = ({ linksList }) => (
linksList
.map(({ url, title, id }) => (
<a
key={id}
className={styles.navLink}
href={url}>
{title}
</a>
))
);
Now in Next app /pages/index.js
import {NavLinks} from '#myCompany/all_components';
.....
export const Home = ({ data }) => {
return ()
};
.bablerc
{
"presets": ["next/babel"]
}
next.config.js
module.exports = {
webpack: (config) => {
config.resolve.extensions = ['.js', '.jsx'];
config.module.rules.push(
{test: /\.(js|jsx)$/, use: {
loader: "babel-loader",
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}}
);
return config;
}
}
But I am getting error -
error - ./node_modules/#myCompany/all_componentss/src/Footer/components/NavLinks /style.module.scss
CSS Modules cannot be imported from within node_modules.
Read more: https://nextjs.org/docs/messages/css-modules-npm
Location: node_modules\#myCompany/all_components\src\Footer\components\NavLinks\index.js
[BABEL] Note: The code generator has deoptimised the styling of C:\Projects\service-page\node_modules\react-dom\cjs\react-dom.development.js as it exceeds the max of 500KB.
wait - compiling /_error (client and server)...
event - compiled client and server successfully in 47.8s (176 modules)
error - SyntaxError: Unexpected token 'export'
Can you please advice what wrong I am doing here.
There's a workaround. You can use next-css. It seems to be a duplicate of https://stackoverflow.com/a/55255918/19135131
Does it help you?

React Storybook SVG Failed to execute 'createElement' on 'Document'

I'm trying to add Storybook to an existing React app but getting errors with imported svg files. The svg is imported and used like:
import Border from './images/border.inline.svg'
...
<Border className="card__border" />
This works when the app is run and built, but I get an error in Storybook. How come?
Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
Error: Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
The default webpack.config.js has:
...
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
},
...
Also, the existing code uses webpack 3, and I'm using Storybook V4.
This is happening because Storybook's default webpack config has its own svg config:
{
test: /\.(svg|ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani)(\?.*)?$/,
loader: 'file-loader',
query: { name: 'static/media/[name].[hash:8].[ext]' }
},
I'm pretty sure this is the cause, because you can see the path outlined in error message: query: { name: 'static/media/[name].[hash:8].[ext]' } -> static/media/border.inline.258eb86a.svg
The solution can be to find the existing loader & change / or add an exclude rule to it. Here's an example of a custom .storybook/webpack.config.js:
// storybook 4
module.exports = (_, _, config) => {
// storybook 5
module.exports = ({ config }) => {
const rules = config.module.rules;
// modify storybook's file-loader rule to avoid conflicts with your inline svg
const fileLoaderRule = rules.find(rule => rule.test.test('.svg'));
fileLoaderRule.exclude = /\.inline.svg$/;
rules.push({
test: /\.inline.svg$/,
...
}],
});
return config;
};
It appears that Storybook V6 they have changed the default Webpack config. I found that the above answers didn't work for me.
They no longer have an SVG rule, therefore testing for SVG will either error or return back undefined.
There is a oneOf rule on the module.rules which contains a loader without a test as the last rule:
{
loader: '/Users/alexwiley/Work/OneUp/resources/client/node_modules/react-scripts/node_modules/file-loader/dist/cjs.js',
exclude: [Array],
options: [Object]
}
This is the culprit, you need to make sure that the file load is excluding all inline SVG file otherwise it will error.
Add the following to your .storybook/main.js file:
webpackFinal: async(config, { configType }) => {
config.module.rules.forEach((rule) => {
if (rule.oneOf) {
// Iterate over the oneOf array and look for the file loader
rule.oneOf.forEach((oneOfRule) => {
if (oneOfRule.loader && oneOfRule.loader.test('file-loader')) {
// Exclude the inline SVGs from the file loader
oneOfRule.exclude.push(/\.inline\.svg$/);
}
});
// Push your SVG loader onto the end of the oneOf array
rule.oneOf.push({
test: /\.inline\.svg$/,
exclude: /node_modules/,
loader: 'svg-react-loader', // use whatever SVG loader you need
});
}
});
return config;
}
In Storybook 6, You have to import it like this:
import { ReactComponent as Border } from './images/border.inline.svg'
Try that if it also works for your version since this question is from a year ago.
This is another way that fixed the issue for me
import Border from './images/border.inline.svg'
And then in your code
<img src={Border} alt="Border" className="w-25"/>
I got it working with
...
module.exports = {
module: {
rules: [
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
}
]
}
}
For me it was happening as I was using wrong tag name:
import React from 'react';
import RMDBLogo from '../../images/react-movie-logo.svg';
import TMDBLogo from '../../images/tmdb_logo.svg';
import { Wrapper, Content,LogoImg,TMDBLogoImg } from './Header.styles';
const Header = () => (
<Wrapper>
<Content>
<LogoImg src={RMDBLogo} alt='RMDBLogo' />
<TMDBLogo src={TMDBLogo} alt='TMDBLogo'/>
</Content>
</Wrapper>
);
export default Header;
I had imported TMDBLogoImg component while I'm using TMDBLogo tag inside Content tag.

driven.js:30491 Uncaught SyntaxError: Unexpected token import which refers to the line in react js application?

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.

css-loader not importing .css file returning empty object

Importing style from css files. Returning empty object. Seems css-loader is not working correctly. Can anyone help me on this. Please find the reference files below
index.js
import React from 'react'
import style from './header.css'
console.log(style) // Returning empty object
export default class Header extends React.PureComponent {
render() {
return(
<header className = {style.header}>
This is header component
</header>
)
}
}
./header.css
.header {
background: #007DC6;
}
./webpack.config.js
{
test: /\.css$/,
exclude: /node_modules/,
loaders: ['style-loader', 'css-loader'],
}, {
test: /\.css$/,
include: /node_modules/,
loaders: ['style-loader', 'css-loader'],
}
I wonder if this is perhaps you are not using css-modules. The example you are showing there is an example of implementing the css-modules feature of the loader.
Perhaps try adding the ?modules query to your css-loader definition.
You can fix your problem with three ways :
#1:
Replace 'css-loader' with 'css-loader?modules=true&camelCase=true'
#2:
Do old school like this :
##index.js
import React from 'react'
import './header.css'
export default class Header extends React.PureComponent {
render() {
return(
<header className="header">
This is header component
</header>
)
}
}
#3:
use babel-plugin-react-css-modules or React CSS Modules

Webpack not bundling node modules imported in dependency JS files

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.

Resources