Webpack Build SyntaxError: Unexpected token ) - javascript

Note: I read through the other similar questions (here and others), but they are all about earlier versions of webpack and babel and do not solve the following issue.
This is serving just fine, but when I run npm run build I'm getting the following error. How do I solve this? (And how do I get better errors than this?, the log is just as bad).
> react_01#1.0.0 build /Users/monkeydo/Documents/code/__tests/react_01
> webpack --mode production
/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack-cli/bin/cli.js:41
)} manually.`,
^
SyntaxError: Unexpected token )
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at runCli (/Users/monkeydo/Documents/code/__tests/react_01/node_modules/webpack/bin/webpack.js:69:2)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react_01#1.0.0 build: `webpack --mode production`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react_01#1.0.0 build script.
My webpack file looks like this:
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
//entry: ['#babel/polyfill', './src/index.js'],
entry: './src/index.js',
// Where files should be sent once they are bundled
output: {
path: path.join(__dirname, '/dist'),
filename: 'index.bundle.js'
},
// webpack 5 comes with devServer which loads in development mode
devServer: {
port: 3000,
watchContentBase: true
},
// Rules of how webpack will take our files, complie & bundle them for the browser
module: {
rules: [
{
test: /\.(js|jsx)$/,
// test: /\.jsx?/,
exclude: /nodeModules/,
use: {
loader: 'babel-loader',
query:
{
presets:['react', 'preset-env']
}
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [new HtmlWebpackPlugin({ template: './src/index.html' }), new MiniCssExtractPlugin()]
}
My package json looks like this:
{
"name": "react_01",
"version": "1.0.0",
"description": "",
"main": "index.jsx",
"scripts": {
"serve": "webpack serve --mode development",
"build": "webpack --mode production"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.14.6",
"#babel/preset-env": "^7.14.7",
"#babel/preset-react": "^7.14.5",
"babel-loader": "^8.2.2",
"css-loader": "^6.0.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.1.0",
"style-loader": "^3.1.0",
"webpack": "^5.45.1",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2"
}
My babelrc file looks like this:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
My index.js file looks like this:
import React from "react"
import ReactDom from "react-dom"
import App from "./components/app"
import "./style.css"
ReactDom.render(<App />, document.getElementById('app'))
My app.js file looks like this:
import React from "react"
function App() {
return (<div>
<h2>Welcome to My new React App</h2>
<h3>Date : {new Date().toDateString()}</h3>
</div>)
}
export default App
*** Edit: not sure what I was thinking... I totally forgot to add the webpack code before :o ! I guess that was a dyslexic senior moment. It's added now.

Just remove the styles import
import "./style.css"
Webpack speaks JavaScript, not css, if you want it to learn it you need to create a webpack config file and use the proper loader to handle css

Related

ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js):

I'm trying to set up ReactJs from scratch but npm start, dev, build, and watch are throwing the error below:
ERROR in ./src/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: C:\da4na4\web\stocker\src\index.js: Unexpected character '�' (1:0)
I have setup package.json, webpack.config.js, and .babelrc configurations. I have equally tried out previous answers on Stack Overflow, yet the issue persist. Below are the configurations of the respective files:
package.json
{
"name": "stocker",
"version": "1.0.0",
"description": "A product inventory web app to help you keep track of your stocks and meet demands",
"main": "webpack.config.js",
"scripts": {
"test": "jest ./src/tests",
"dev": "webpack --mode development",
"build": "webpack --mode production",
"watch": "webpack --watch",
"start": "webpack serve --mode development --open --hot"
},
"keywords": [
"products",
"Inventory"
],
"author": "Emmanuel Joshua",
"license": "MIT",
"devDependencies": {
"#babel/core": "^7.12.16",
"#babel/preset-env": "^7.12.16",
"#babel/preset-react": "^7.12.13",
"#webpack-cli/serve": "^1.3.0",
"babel-loader": "^8.2.2",
"css-loader": "^5.0.2",
"html-loader": "^1.3.2",
"html-webpack-plugin": "^5.0.0",
"jest": "^26.6.3",
"jsdom": "^16.4.0",
"sass-loader": "^11.0.1",
"style-loader": "^2.0.0",
"webpack": "^5.21.2",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
},
"dependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
}
}
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const htmlPlugin = new HtmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html"
});
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "public"),
filename: "js/app.min.bundle.js",
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(scss|css)$/, use: ["sass-loader", "css-loader", "style-loader"]
},
{
test: /\.(html)$/, use: ["html-loader"]
}
],
},
plugins: [htmlPlugin],
target:"node",
devServer:{
port: 3000,
contentBase: path.resolve(__dirname, "public")
},
resolve: {
extensions: ["*", ".js", ".jsx"],
},
};
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
These are the index.js and the App.js files
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
ReactDOM.render(
<App firstname={"Joshua"} />,
document.getElementById("root")
)
js/App.js
import React, {Component} from 'react';
class App extends Component{
constructor(props){
super(props);
}
render(){
return(
<h1>Hello {this.props.firstname}, Welcome to our Website!</h1>
)
}
}
export default App;
This tripped me a while. I found out one of the reasons is because of the directory naming path.
I used # for a folder name and it gave me the same error you're reading into.
e.g. my path
C:/Users/johndoes/codes/# wip/project1/sub/
My suggestion is looking at the pathing and seeing if everything is on the right place and referred to correctly.

Module build failed Cannot find module '#babel/preset-env'

I was working on my react application with set up babel. Unfortunately while setting it up using yarn and when I build my bundle.js file, I run into some problems:
ERROR in ./src/app.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
Error: Cannot find module '#babel/preset-env' from '/Users/react-file/Desktop/indecision'
at Function.resolveSync [as sync] (/Users/react-file/Desktop/indecision/node_modules/resolve/lib/sync.js:89:15)
at resolveStandardizedName (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/files/plugins.js:101:31)
at resolvePreset (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/files/plugins.js:58:10)
at loadPreset (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/files/plugins.js:77:20)
at createDescriptor (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-descriptors.js:154:9)
at /Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-descriptors.js:109:50
at Array.map (<anonymous>)
at createDescriptors (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-descriptors.js:109:29)
at createPresetDescriptors (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-descriptors.js:101:10)
at presets (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-descriptors.js:47:19)
at mergeChainOpts (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-chain.js:320:26)
at /Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-chain.js:283:7
at Generator.next (<anonymous>)
at buildRootChain (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/config-chain.js:120:29)
at buildRootChain.next (<anonymous>)
at loadPrivatePartialConfig (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/partial.js:95:62)
at loadPrivatePartialConfig.next (<anonymous>)
at Function.<anonymous> (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/partial.js:120:25)
at Generator.next (<anonymous>)
at evaluateSync (/Users/react-file/Desktop/indecision/node_modules/gensync/index.js:244:28)
at Function.sync (/Users/react-file/Desktop/indecision/node_modules/gensync/index.js:84:14)
at Object.<anonymous> (/Users/react-file/Desktop/indecision/node_modules/#babel/core/lib/config/index.js:41:61)
at Object.<anonymous> (/Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:151:26)
at Generator.next (<anonymous>)
at asyncGeneratorStep (/Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:3:103)
at _next (/Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:5:194)
at /Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:5:364
at new Promise (<anonymous>)
at Object.<anonymous> (/Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:5:97)
at Object._loader (/Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:231:18)
at Object.loader (/Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:64:18)
at Object.<anonymous> (/Users/react-file/Desktop/indecision/node_modules/babel-loader/lib/index.js:59:12)
Here's my package.json:
{
"name": "Box",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"server": "live-server public/",
"build": "webpack --watch",
"build-babel": "babel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch"
},
"dependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"live-server": "^1.2.1",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"validator": "^13.0.0",
"webpack": "^4.43.0"
},
"devDependencies": {
"#babel/core": "^7.9.6",
"webpack-cli": "^3.3.11"
}
}
Here's my webpack.config.js const path = require('path');
module.exports = {
entry: './src/app.js',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}]
}
};file"
And here's my .babelrc file:
{
"presets": [
"env",
"react"
]
}
Any idea what's wrong with this?
You need to install #babel/preset-env instead of babel-preset-env.
I believe that most babel modules now live under the #babel org
Edit:
also IMHO the correct syntax for the babelrc file should be
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
}

Trying to build ReactJS app in prod - Module build failed: SyntaxError: Unexpected token

Its been a while since I've pushed my React app to a prod environment after a bunch of changes (dumb, I know) and now when I try to build it for prod the build is failing and I'm getting the following error:
ERROR in ./src/app.js
Module build failed: SyntaxError: Unexpected token (9:16)
7 |
8 |
> 9 | ReactDOM.render(<AppRouter />, document.getElementById('app'));
| ^
10 |
11 |
# multi #babel/polyfill ./src/app.js
error Command failed with exit code 2.
Here's my webpack.config.js file:
const path = require('path');
module.exports = (env) => {
const isProduction = env === 'production';
console.log(env);
return {
entry: ["#babel/polyfill", "./src/app.js"],
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}]
},
devtool: isProduction ? 'source-map' : 'cheap-module-eval-source-map',
devServer: {
contentBase: path.join(__dirname, 'public'),
historyApiFallback: true
}
};
};
And here's my package.json file:
{
"name": "SheSaysGo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"serve": "live-server public/",
"build:dev": "webpack",
"build:prod": "webpack -p --env production",
"dev-server": "webpack-dev-server",
"start": "node server/server.js"
},
"dependencies": {
"#babel/polyfill": "^7.4.4",
"babel-cli": "6.24.1",
"babel-core": "6.25.0",
"babel-loader": "7.1.1",
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
"chaituvr-react-graphjs-test": "^0.0.3",
"cosmicjs": "^3.2.17",
"express": "4.15.4",
"google-maps-react": "^2.0.2",
"live-server": "^1.2.1",
"lodash": "^4.17.11",
"react": "16.0.0",
"react-dom": "16.0.0",
"react-leaf-carousel": "^1.2.2",
"react-router-dom": "4.2.2",
"validator": "8.0.0",
"webpack": "3.1.0",
"webpack-dev-server": "2.5.1"
}
}
It builds when I run it locally as a dev build with "yarn run dev-server" but not when I run "yarn run build:prod".
EDIT: Sorry I had written .babel.rc, it's .babelrc
Getting babel-loader to use preset-react
It looks like Babel is interpreting your file as regular JavaScript, as opposed to React JSX (or whatever it's called).
I see in your package.json that you're using #babel/preset-react, so it should work if well configured.
In .babelrc
Check your .babelrc file, it should contain something like this:
{
"presets": ["#babel/preset-react"]
}
You can also change the extension of the file to .jsx, it find it to be clearer, but that's up to your personal preference.
In webpack.config.js
Alternatively, you can define this in the webpack config. Replace this:
loader: 'babel-loader',
with this (in your webpack.config.js):
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
},
Check the package's name
Looking closer at your package.json, it contains:
"babel-preset-env": "1.5.2",
"babel-preset-react": "6.24.1",
But you're using #babel/preset-env and #babel/preset-react. So npm install --save those and remove the old ones from your package.json.
Run babel --presets #babel/preset-react ./src/app.js, to see if the preset is there and works:
Running it should print to the console:
ReactDOM.render(React.createElement(AppRouter, null), document.getElementById('app'));
^ this is babel successfully converting JSX to JS.

webpack error : CLI moved into a separate package: webpack-cli

I'm following a tutorial here to install react and I'm new to ReactJS.
I completed installations as shown in the video and run this command in the root project folder:
npm start it
I encountered with following error here:
The CLI moved into a separate package: webpack-cli
Please install 'webpack-cli' in addition to webpack itself to use the CLI
-> When using npm: npm i -D webpack-cli
-> When using yarn: yarn add -D webpack-cli
module.js:471
throw err;
^
Error: Cannot find module 'webpack-cli/bin/config-yargs'
at Function.Module._resolveFilename (module.js:469:15)
I tried the solutions posted in this link but it's still the same.
Here's webpack.config.js:
var path = require('path');
module.exports = {
entry: './script.jsx',
output: {
path: path.resolve(__dirname,''),
filename: 'transpiled.js'
},
module: {
rules: [
test: /\.jsx?$/,
loaders: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
]
}
}
And package.json:
{
"name": "react_project",
"version": "1.0.0",
"description": "first project on react",
"main": "index.js",
"scripts": {
"it": "webpack-dev-server --hot"
},
"author": "azima",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^8.0.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"webpack": "^4.17.1",
"webpack-dev-server": "^3.1.7"
},
"dependencies": {
"react": "^16.4.2",
"react-dom": "^16.4.2"
}
}
Is it the issue with Webpack version?
Try npm install webpack-cli --save

Webpack 2 'cannot find /'

I am pretty new to this, but while upgrading to webpack 2 and adding jsx support to my project, I changed the gonfig rules to match what the api calls for in Webpack 2 and added babel-loader. All I am seeing in the browser is "cannot find /".
When I run DEBUG=express:* node index.js
I get:
.../Sites/practice/index.js:1
(function (exports, require, module, __filename, __dirname) { import React from 'react'
^^^^^^
SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:146:18)
at node.js:404:3
webpack.config.js
var webpack = require('webpack')
module.exports = {
entry: './index.js',
output: {
path: 'public',
filename: 'bundle.js',
publicPath: '/'
},
plugins: process.env.NODE_ENV === 'production' ? [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin()
] : [],
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: { presets: ['es2015', 'react'] },
}],
},
{
test: /\.jsx$/,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: { presets: ['es2015', 'react'] },
}],
}
]
},
resolve: {
extensions: [
'.jsx',
'.js',
]
},
}
server.js
var express = require('express')
var path = require('path')
var compression = require('compression')
var React = require('react')
var renderToString = require('react-dom/server')
var RouterContext = require('react-router')
var match = require('react-router')
var routes = require('./modules/routes')
var app = express()
app.use(compression())
// serve our static stuff like index.css
app.use(express.static(path.join(__dirname, 'public'), {index: false}))
// send all requests to index.html so browserHistory works
app.get('*', (req, res) => {
match({ routes, location: req.url }, (err, redirect, props) => {
if (err) {
res.status(500).send(err.message)
} else if (redirect) {
res.redirect(redirect.pathname + redirect.search)
} else if (props) {
// hey we made it!
const appHtml = renderToString(<RouterContext {...props}/>)
res.send(renderPage(appHtml))
} else {
res.status(404).send('Not Found')
}
})
})
function renderPage(appHtml) {
return `
<!doctype html public="storage">
<html>
<meta charset=utf-8/>
<title>My First React Router App</title>
<link rel=stylesheet href=/index.css>
<div id=app>${appHtml}</div>
<script src="/bundle.js"></script>
`
}
var PORT = process.env.PORT || 8080
app.listen(PORT, function() {
console.log('Production Express server running at localhost:' + PORT)
})
index.js
import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import routes from './modules/routes'
render(
<Router routes={routes} history={browserHistory}/>,
document.getElementById('app')
)
and package.json:
{
"name": "tutorial",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
"start:dev": "webpack-dev-server --inline --content-base public/ --history-api-fallback",
"start:prod": "npm run build && node server.bundle.js",
"build:client": "webpack",
"build:server": "webpack --config webpack.server.config.js",
"build": "npm run build:client && npm run build:server"
},
"author": "",
"license": "ISC",
"dependencies": {
"compression": "^1.6.1",
"express": "^4.13.4",
"if-env": "^1.0.0",
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.28.0",
"extract-text-webpack-plugin": "^2.1.0",
"http-server": "^0.8.5",
"sass-loader": "^6.0.3",
"static-site-generator-webpack-plugin": "^3.4.1",
"style-loader": "^0.16.1",
"webpack": "^2.2.1",
"webpack-dev-server": "^1.14.1"
}
}
I know i am missing something, but do not know what. I already searched here and tried other suggestions but none of them worked for me.
structure:
-root
-modules
-routes.js
-App.jsx
-othercomponents...
-node_modules
-public
-index.html
-index.css
-data.js
-index.js
-package.json
-server.js
-webpack.config.js
-webpack.server.config.js
-index.js
I think there might be two separate issues:
I am seeing in the browser is "cannot find /".
This looks like an express problem, is the response status 404? In your express server try changing:
app.get('*', (req, res) => {
to:
app.get('/', (req, res) => {
import React from 'react'
SyntaxError: Unexpected token import
This is a node error - node.js does not support ES6 module imports like this. You can change the execution environment to something like babel-node and it should work.
This is actually something I am trying to investigate solutions for - babel-node indicates it is not for production use, but I am having difficulting finding a way to write code in ES6 but use it on the server as well where it is not being processed through a transpiler.

Categories