Hello I tried to search in other questions but none of mentioned solutions I tried did not work for me.
When using command:
npm start
I have an error:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: D:/Kodilla/Projekty/webpack-to-do-app/src/index.js: Unexpected > token (6:4)
5 | ReactDOM.render(
6 | <App />,
| ^
7 | document.getElementById('app')
8 | );
Defined command in package.json:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack"
},
index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/App';
ReactDOM.render(
<App />,
document.getElementById('app')
);
App.js file:
import React from 'react';
import uuid from 'uuid';
import style from './App.css';
class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: []
};
}
addTodo(val){
const todo = {
text: val,
id: uuid.v4(),
};
const data = [...this.state.data, todo];
this.setState({data});
}
removeTodo(id) {
const remainder = this.state.data.filter(todo => todo.id !== id);
this.setState({data: remainder});
}
render() {
return (
<div className={style.TodoApp}>
Tutaj pojawią się komponenty naszej aplikacji.
</div>
);
}
}
export default App;
webpack.config.js file:
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
loader: "babel-loader"
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true
}
}
]
}
]
}
};
.babelrc file:
{
"presets": [
["env", "react"]
]
}
Link to repository
Edit:
I tried the solution from post you suggest I duplicate but copied 1:1 did not work for me. I changed my webpack config to:
module: {
loaders: [...
{
test: /\.(js|jsx)?$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}]
},
and problem still occurrs. I think I may be doing something wrong in other place than in mentioned example.
Edit 2:
I use babel-core#6.26.3 and babel-loader#7.1.5 because these are requirement of the project.
React and react-dom dependencies installed.
Presets: react. env, es2015, stage-0 installed by
npm install babel-preset-... --save-dev.
First suggested .babelrc config done:
"presets": ["react", "es2015", "stage-0"]
Error occurrs:
Couldn't find preset "#babel/preset-env" relative to directory
"...webpack-to-do-app\node_modules\css-loader"
What am I still doing wrong?
Problem was solved.
Things that helped:
1. Update presets from babel-env, babel-react to #babel/preset-env and #babel/preset-react. #babel-core was installed but babel-core stayed on place. Final set:
"devDependencies": {
"#babel/core": "^7.2.2",
"#babel/preset-env": "^7.2.3",
"#babel/preset-react": "^7.0.0",
"babel": "^6.23.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.4",
"css-loader": "^2.1.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"style-loader": "^0.23.1",
"webpack": "^4.28.2",
"webpack-cli": "^3.1.2"
},
2. Uninstall and install babel-loader which caused problem with requiring wrong version of babel itself.
#Alireza your suggestion was partially right. Thanks for helping.
please consider put below config on your .babelrc
{
"presets": ["react", "es2015", "stage-0"]
}
it should work.
also i see that you have nested array inside "presets". every preset should be one of presets elements.
and i'm strongly recommend that you use latest babel(version 7). when you upgrade to babel 7 you should download #babel/preset-react and #babel/preset-env and that should be enough.
and .babelrc will look like this:
{
"presets": [
"#babel/react",
"#babel/env"
]
}
Related
My goal:
I am creating a React component library in JavaScript with Webpack 5 and Babel 7 that is published to npm. I want consumers to import individual components into their React apps. I also want to add a development server for stakeholders to add components to the component library.
When running the app locally with 'npm run build && npm run serve' (npx webpack serve) I keep getting this error message:
ERROR in ./src/index.js 20:2
Module parse failed: Unexpected token (20:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| root.render(
> <App />
| );
Here is my setup:
./webpack.config.common.js
const path = require('path');
module.exports = {
entry: {
index: './src/index.js',
MyCoolButton: './src/components/buttons/MyCoolButton',
RandomButton: './src/components/buttons/RandomButton',
StyledButton: './src/components/buttons/StyledButton',
theme: './src/tokens/Theme'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
optimization: {
runtimeChunk: 'single',
},
resolve: {
alias: {
path: path.resolve(__dirname, 'src')
},
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
"style-loader",
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
],
},
{
// The test property identifies which file or files should be transformed
test: /\.(js|jsx)$/,
resolve: {
extensions: [".js", ".jsx"]
},
exclude: /[\\/]node_modules[\\/]/,
// The use property indicates which loader should be used to do the transforming.
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
},
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
}
],
},
};
./webpack.config.prod.js
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.config.common');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = merge(commonConfig, {
mode: 'production',
// do not include source maps on prod build
// devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Load css to separate file
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
'css-loader',
// Compiles Sass to CSS
'sass-loader',
],
},
],
},
optimization: {
// minimize: true,
minimizer: [
// For webpack#5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
// `...`,
new CssMinimizerPlugin({
test: /\.foo\.css$/i,
}),
new TerserPlugin({
terserOptions: {
parse: {
// We want terser to parse ecma 8 code. However, we don't want it
// to apply minification steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the `compress` and `output`
ecma: 8,
},
compress: {
ecma: 5,
inline: 2,
},
mangle: {
// Find work around for Safari 10+
safari10: true,
},
output: {
ecma: 5,
comments: false,
}
},
// Use multi-process parallel running to improve the build speed
parallel: true,
}),
],
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'styles.[contenthash].css',
})
],
// As you publish your code as React component, apart from set React as peer dependency you have to set the react as externals to use the react at the consumer library.
externals: {
'react': {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React'
},
'react-dom': {
commonjs: 'react-dom',
commonjs2: 'react-dom',
amd: 'ReactDOM',
root: 'ReactDOM'
}
},
});
./babel.config.js
{
"plugins": [
"babel-plugin-module-resolver"
],
"presets": [
["#babel/preset-env"], // instead of "#babel/preset-es2015",
["#babel/preset-react"]
]
}
./src/index.js
export {default as MyCoolButton} from './components/buttons/MyCoolButton';
export {default as RandomButton} from './components/buttons/RandomButton';
export {default as StyledButton} from './components/buttons/StyledButton';
export {theme} from './tokens/Theme';
import './tokens/theme.scss'; // need import to generate minified css flat file
// kitchen sink for component development
import React from "react";
import { createRoot } from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('app');
const root = createRoot(rootElement);
root.render(
<App />
);
App.jsx
import React, { Component } from 'react';
import StyledButton from "./components/buttons/StyledButton";
import RandomButton from "./components/buttons/RandomButton";
class App extends Component {
render() {
return (
<div>
<div className='container body'>
<div className='row'>
<div className='col-12 text-center mb-4 mt-4'>
<h1>Welcome to the Kitchen Sink Page</h1>
</div>
<div className='col-6'>
<RandomButton />
</div>
<div className='col-6'>
<StyledButton />
</div>
</div>
</div>
</div>
);
}
}
export default App;
and my package.json
...
"peerDependencies": {
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"babel-core": "^6.0.0",
"webpack": "^4.0.0"
},
"devDependencies": {
"#babel/cli": "^7.17.0",
"#babel/core": "^7.17.2",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"#semantic-release/changelog": "^6.0.1",
"#semantic-release/commit-analyzer": "^9.0.2",
"#semantic-release/git": "^10.0.1",
"#semantic-release/npm": "^9.0.0",
"#semantic-release/release-notes-generator": "^10.0.3",
"#testing-library/react": "^12.1.2",
"babel-core": "^7.0.0-bridge.0",
"babel-loader": "^7.1.5",
"babel-plugin-module-resolver": "^4.1.0",
"commitizen": "^4.2.4",
"css-loader": "^6.6.0",
"css-minimizer-webpack-plugin": "^3.4.1",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^8.8.0",
"eslint-plugin-jest": "^26.1.0",
"eslint-plugin-react": "^7.28.0",
"jest": "^27.5.0",
"path": "^0.12.7",
"prop-types": "^15.6.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"sass": "^1.49.7",
"sass-loader": "^12.4.0",
"semantic-release": "^19.0.2",
"style-loader": "^1.3.0",
"styled-components": "^5.3.3",
"webpack": "^5.68.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"dependencies": {
"babel-plugin-styled-components": "^2.0.2",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^4.0.0",
"html-webpack-plugin": "^5.5.0",
"mini-css-extract-plugin": "^2.5.3",
"optimize-css-assets-webpack-plugin": "^6.0.1",
"terser-webpack-plugin": "^5.3.1",
"webpack-merge": "^5.8.0"
},
...
I have browsed countless stackoverflow posts and answers, blog posts and I am having a hard time debugging this 'unexpected token' error.
I am new to Webpack so if anyone can see if I am doing something wrong in the Webpack config files, in way the React app is being bundled, or by loading Babel loaders, I would really appreciate some pointers.
getting an error when executing my react module
'classProperties' isn't currently enabled (44:11):
}
43 | // componentDidUpdate or try this
> 44 | onClick = (e) => {
| ^
45 | e.preventDefault();
46 | const url = `${this.props.url}`;
47 | if(this.props.method === "GET"){
Add #babel/plugin-proposal-class-properties (https://git.io/vb4SL) to
the 'plugins' section of your Babel config to enable transformation.
I tried the solutions still get the error after re building.
Support for the experimental syntax 'classProperties' isn't currently enabled
package.json
{
"name": "blahmodule",
"version": "1.0.0",
"description": "a fetch module for our project",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "./node_modules/.bin/babel src --out-file index.js"
},
"peerDependencies": {
"react": "^16.6.6",
"react-dom": "^16.6.3",
"axios": "^0.19.0"
},
"author": "",
"license": "ISC",
"dependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/preset-react": "^7.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.4.4",
"axios": "^0.19.0"
}
}
.babelrc
I tried changing the .babelrc to babel.config.js with module.exports, but still no success. also with and without "loose": true
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
code from the beginning
import React, {Component} from 'react';
import axios from 'axios';
class MyFetch extends Component {
constructor(props){
super(props);
this.state = {
data:[],
startTime:'',
responseTime:''
}
}
componentWillMount(){
.....
}
// componentDidUpdate or try this
onClick = (e) => {
e.preventDefault();
const url = `${this.props.url}`;
if(this.props.method === "GET"){
axios.get(url).then( res => {
this.setState({
data: res.data
})
console.log(this.state.data)
})
}
else if(this.props.method === "POST"){
axios.get(url).then( res => {
this.setState({
data: res.data
})
console.log(this.state.data)
})
}
}
render(){
return (
<div>
{this.props.url ? (
<button onClick={this.onClick}>Get Response Time</button>
):(
null
)}
{this.state.responseTime ? (
<h3>{this.state.responseTime}</h3>
):(
null
)}
</div>
);
}
}
export default MyFetch;
Fixed it by adding webpack, i deleted .babelrc because i included in webpack.config.js. Now i guess i have a reason to use webpack in my projects.
var path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, './'),
filename: 'index.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/react'],
plugins:['#babel/plugin-proposal-class-properties']
}
}
}
]
},
externals: {
'react': 'commonjs react',
'reactDOM': 'react-dom'
},
};
For beginners, the best way to start working on React is to use create-react-app to create a ready to go clean boilerplate. Have a look at the docs and don't waste time configuring things but focus on writing code for your app.
https://github.com/facebook/create-react-app#npm
I'm new to react and I'm importing using esmodules but I keep getting an error telling react is undefined. I'm running it through babel and then bundling it with webpack. I've looked at some of the other related questions but none seem to be helping with my problem. Why is it comming up undefined and how can I fix it?
Error:
Uncaught ReferenceError: React is not defined
at Object.<anonymous> (bundle.js:formatted:76)
at n (bundle.js:formatted:11)
at bundle.js:formatted:71
at bundle.js:formatted:72
package.json:
{
"name": "reactTestProject",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Brandon Lind",
"license": "MIT",
"devDependencies": {
"#babel/cli": "^7.2.3",
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3"
},
"dependencies": {
"#babel/polyfill": "^7.2.5",
"react": "^16.8.4"
}
}
files:
filename: app.js
import Square from "./SquareDiv.js";
let main= document.getElementsByTagName("main")[0];
console.log("wtf")
main.appendChild(<Square/>);
filename: SquareDiv.js
import React from "react";
class Square extends React.Component{
constructor(props){
super(props);
this.state={
isOn: true
}
}
getIsOn(){
let currentState= this.state.isOn;
let pastState= state;
if(currentState===false){
currentState===true;
}
else {
currentState ===false;
}
return pastState;
}
render(){
<div onClick={getIsOn} class="square">this.state.isOn</div>
}
}
export {Square};
babel.config.js:
const presets=[
[
"#babel/preset-env",
{
targets:{
esmodules: true,
edge: 10,
chrome: 30,
safari: 30,
firefox: 30,
opera: 30
}
}
],
[
"#babel/preset-react",
{
pragma: "pragma",
pragmaFrag: "pragmaFrag",
throwIfNamespace: false
}
]
];
module.exports={
presets
};
webpack.config.js:
module.exports={
entry: "./src/app.js",
output:{
filename: "bundle.js"
},
module:{
rules:[
{ test: /\.m?js$/,
exclude: /(node_modules|browsers_components)/,
use:{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env","#babel/preset-react"]
}
}
}
]
}
}
Don't use this syntax import React from "./node_modules/react";.
It will work only for files that are created in the root directory, and your components are likely in src/.
Webpack will resolve everything for you, so you can just use import React from 'react'; everywhere.
Also replace this string: export {Square}; with export default Square
And you can omit .js extension when import, so you can write it this way: import Square from "./SquareDiv";
If you don't want to use default export, you should use import {Square} from "./SquareDiv"
You can read the differences between default and regular exports here
You have a lot of problems in your code snippet. I mentioned some of them in my answer. There are more of them:
Don't use class keyword in JSX, it should be className
Use curly braces to render JS values like this.state.isOn
When you use handlers, don't use it like onClick={getIsOn}, use onClick={() => getIsOn()} and etc.
I suggest you to go through React tutorial which will save your time a lot!
App.js needs to import react. Every file that has JSX in it has to import react.
This particular error is happening because the JSX for Square in app.js is getting transpiled into a React method call, and since you haven’t imported React in app.js, React is not defined.
UPDATE
Also, this will fix a couple other errors...
Change <div onClick={getIsOn} class="square">this.state.isOn</div> to:
return <div onClick={this.getIsOn} className="square">{this.state.isOn}</div>
I'm trying to migrate my app to webpack 4. My head hurts already.
Dynamic imports - this is my method of code splitting (page by page). But I can't get it to work. Have set up very simple tester with following packages:
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-plugin-transform-async-to-generator": "^6.24.1",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.4.0",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
}
Here is my main test app:
import React from "react";
import ReactDOM from "react-dom";
import style from "./main.css";
import pageLoader from './pageLoader';
class App extends React.Component {
render() {
let page = pageLoader();
return (
<div>
<p>React here!</p>
{page}
</div>
);
}
};
export default App;
ReactDOM.render(<App />, document.getElementById("app"));
and my page I want to load dynamically with separate bundle.
import React from "react";
import ReactDOM from "react-dom";
import style from "./main.css";
const Page1 = () => {
return (
<div>
<p>Page1 here!</p>
</div>
);
};
export default Page1;
Here's my webpack.config so far:
const path = require('path');
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: {
polyfill: 'babel-polyfill',
app: './src/index.js'
},
output: {
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js', //name of non-entry chunk files
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: { minimize: true }
}
]
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
Now here's the part that errors on build. Here's the function which calls the dynamic import:
function pageLoader() {
return import(/* webpackChunkName: "page1" */ './Page1')
.then(page => {
return page.default;
});
}
export default pageLoader;
I get this error on build:
ERROR in ./src/test/pageLoader.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (2:8)
1 | function pageLoader() {
> 2 | return import(/* webpackChunkName: "page1" */ './Page1')
| ^
3 | .then(page => {
4 | return page;
5 | });
Everything I have read says this is the way to set this up. What am I doing wrong?
I was facing the same issue the fix was:
npm install --save-dev #babel/plugin-syntax-dynamic-import
add following line to .babelrc
"plugins": ["#babel/plugin-syntax-dynamic-import"],
Sources:
https://webpack.js.org/guides/code-splitting/#dynamic-imports
https://babeljs.io/docs/plugins/syntax-dynamic-import/#installation
Just an update for those going down this path: If you are using React, I would recommend react-loadable, makes it extremely easy to do dynamic imports on a per-component basis... a lot of large companies use it.
I'm learning react and flux, and in lesson 1 the tutorial has failed me.
This tutorial immediately breaks on 'npm start' with the following errors:
ERROR in ./src/js/main.js
Module parse failed: /Users/me/Projects/egghead-flux/src/js/main.js Unexpected token (4:16)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (4:16)
at Parser.pp$4.raise (/Users/me/Projects/egghead-flux/node_modules/acorn/dist/acorn.js:2221:15)
It doesn't seem to understand ReactDOM.render(<App />, document.getElementById('main')); I assume parsing the JSX <App /> part is failing.
Has anyone encountered this issue before? Removing / reinstalling node modules does nothing. Is there some setup step missing from the video?
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
ReactDOM.render(<App />, document.getElementById('main'));
App.js
import React from 'react';
export default class App extends React.Component {
render(){
return <h1>Flux</h1>
}
}
webpack.config.js
module.exports = {
entry: './src/js/main.js',
output:{
path:'./dist',
filename: 'bundle.js',
publicPath: '/'
},
devServer: {
inline: true,
contentBase: './dist'
},
module: {
loaders: [
{
test: '/\.jsx?$/',
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query:{
presets: ['es2015', 'react']
}
}
]
}
}
package.json
{
"name": "egghead-flux",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"flux": "^3.1.0",
"react": "^15.3.2",
"react-dom": "^15.3.2",
"react-router": "^3.0.0"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-loader": "^6.2.7",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"webpack": "^1.13.3",
"webpack-dev-server": "^1.16.2"
}
}
Turns out:
test: '/\.jsx?$/',
should be:
test: /\.jsx?$/,
Dammit.