Webpack throws error when trying to build JSX - javascript

There are so many answers to this question on SO, I swear i've tried them all. I am not sure what is wrong with config setup
The Error I get when running webpack in the terminal:
ERROR in ./src/index.js 13:8
Module parse failed: Unexpected token (13:8)
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
| // const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
| return (
> <HomeShell/>
| );
| };
my index.js
import "#babel/polyfill";
import React from 'react';
import ReactDOM from 'react-dom';
import HomeShell from "./HomeShell";
const Root = () => {
return (
<HomeShell/>
);
};
ReactDOM.render(<Root />, document.getElementById('#main'));
^^ HomeShell is js file with React Components that are all js files.
My webpack.config.cjs
import path from 'path';
module.exports = {
entry: ["#babel/polyfill", "./src/index.js"],
output: {
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js'
},
target: "web",
mode: 'production',
module: {
rules: [
{
test: /\.m?js$/,
include: /src/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ["#babel/preset-env", "#babel/preset-react"]
}
}
},
{
test: /\.css$/,
include: /node_modules/,
loader: ['style-loader', 'css-loader'],
}
]
},
};
my .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
my package.json
{
"name": "site name here",
"version": "1.0.0",
"description": "site desc",
"main": "index.js",
"type": "module",
"repository": {
"type": "git",
"url": "git url"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "issues url"
},
"homepage": "readme url",
"dependencies": {
"#babel/polyfill": "^7.10.1",
"#types/express": "^4.17.6",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"nodemailer": "^6.4.5",
"path": "^0.12.7",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"react-redux": "^7.2.0",
"react-router": "^5.1.2",
"react-router-dom": "^5.1.2",
"redux": "^4.0.5"
},
"devDependencies": {
"#babel/cli": "^7.8.4",
"#babel/core": "^7.9.0",
"#babel/preset-env": "^7.9.0",
"#babel/preset-react": "^7.9.4",
"babel-loader": "^8.1.0",
"css-loader": "^3.5.3",
"file-loader": "^5.1.0",
"html-loader": "^1.1.0",
"html-webpack-plugin": "^4.3.0",
"image-webpack-loader": "^3.6.0",
"style-loader": "^1.2.1",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.11"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rm -rf dist && mkdir dist && webpack && babel server -s -d dist",
"clean": "rm -rf dist",
"production": "npm run build && node bin/production",
"start": "npm run production"
}
}
I am far from an expert on react/webpack/babel but this exact setup seems to work fine on another basic app I have running. Not sure what I am doing different between the two apps.

You mentioned that you are using a webpack.config.cjs file, which at the moment anyway, Webpack does not support by default: https://github.com/webpack/webpack-cli/issues/1165
You'd need to explicitly pass --config webpack.config.cjs option to load this file.

I see
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
in your .babelrc file and also in the loader options. Maybe there is a conflict.

Related

Updating Electron issue: Uncaught ReferenceError: global is not defined

I'm working on an Electron app with ReactJS + Bootstrap and Typescript, and as I tried to update my Electron version (11.5.0) to the current one (15.2.0) I stumbled upon this error message in the developer tools' console:
Ignore the warning since it was there before I updated Electron to a more recent version, the problem is that the app is completely blank and unusable. I tried googling and searching here in SO for the message but most posts and answers were related to Angular and a "polyfills.ts" file.
I also tried updating to a lower version (12.2.2) but it broke as well.
├── #types/electron-devtools-installer#2.2.0
├── electron-builder#22.13.1
├── electron-devtools-installer#3.2.0
├── electron-fetch#1.7.4
├── electron-rebuild#3.2.3
├── electron#12.2.2
This is my package.json:
{
"name": "asdfasdf",
"version": "1.0.0",
"main": "./dist/main.js",
"preload": "./dist/preload.js",
"scripts": {
"dev": "concurrently --success first \"npm run dev:electron\" \"npm run dev:react\" -k",
"dev:electron": "NODE_ENV=development webpack --config webpack.electron.config.babel.js --mode development && electron .",
"dev:react": "NODE_ENV=development webpack serve --config webpack.react.config.babel.js --mode development",
"build:electron": "NODE_ENV=production webpack --config webpack.electron.config.babel.js --mode production",
"build:react": "NODE_ENV=production webpack --config webpack.react.config.babel.js --mode production",
"build": "npm run build:electron && npm run build:react",
"rebuild": "electron-rebuild -f -w serialport",
"pack": "electron-builder --dir",
"dist": "electron-builder",
"lint": "eslint .",
"format": "prettier --write \"**/*.+(js|jsx|json|yml|yaml|css|md|vue)\""
},
"keywords": [],
"license": "MIT",
"build": {
"files": [
"dist/",
"node_modules/",
"package.json"
],
"productName": "asdfasdf",
"appId": "com.example.app",
"directories": {
"output": "dist"
}
},
"browser": {
"[module-name]": false
},
"devDependencies": {
"#babel/preset-env": "^7.15.8",
"#babel/preset-react": "^7.14.5",
"#babel/preset-typescript": "^7.15.0",
"#babel/register": "^7.15.3",
"#types/electron-devtools-installer": "^2.2.0",
"#types/firmata": "^0.19.3",
"#types/node": "^16.11.6",
"#types/plotly.js": "^1.54.16",
"#types/react-plotly.js": "^2.2.4",
"#types/react-router-dom": "^5.3.2",
"#types/regenerator-runtime": "^0.13.0",
"dpdm": "^3.8.0",
"electron": "^11.5.0",
"electron-builder": "^22.13.1",
"electron-devtools-installer": "^3.1.1",
"electron-rebuild": "^3.2.3",
"eslint": "^8.1.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"husky": "^7.0.4",
"ify-loader": "^1.1.0",
"lint-staged": "^11.2.6",
"prettier": "^2.4.1",
"react-router-dom": "^5.3.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.4.0"
},
"dependencies": {
"#babel/core": "^7.15.8",
"#serialport/bindings": "^9.2.4",
"#types/johnny-five": "^1.3.1",
"#types/react": "^17.0.33",
"#types/react-dom": "^17.0.10",
"axios": "^0.24.0",
"babel-loader": "^8.2.3",
"bindings": "^1.5.0",
"bootstrap": "^5.1.3",
"concurrently": "^6.3.0",
"core-js": "^3.19.0",
"css-loader": "^6.5.0",
"electron-fetch": "^1.7.4",
"firmata": "^2.3.0",
"ini": "^2.0.0",
"johnny-five": "^2.1.0",
"jquery": "^3.5.1",
"node-gyp": "^8.3.0",
"nodebots-interchange": "^2.1.3",
"plotly.js": "^2.5.1",
"react": "^17.0.1",
"react-bootstrap": "^2.0.0",
"react-dom": "^17.0.1",
"react-google-login": "^5.2.2",
"react-icons": "^4.3.1",
"react-plotly.js": "^2.5.1",
"serialport": "^9.2.4",
"style-loader": "^3.3.1"
},
"husky": {
"hooks": {
"pre-commit": "npm run lint && npm run format"
}
},
"lint-staged": {
"*.+(js|jsx)": "eslint --fix",
"*.+(json|css|md)": "prettier --write"
}
}
I also have these two Webpack config files:
webpack.electron.config.babel.js
import { resolve as _resolve } from "path";
export const resolve = {
extensions: [".tsx", ".ts", ".js"],
};
export const devtool = "source-map";
export const entry = {
main: {
import: "./electron/main.ts",
dependOn: "preload",
},
preload: "./electron/preload.ts",
};
export const output = {
path: _resolve(__dirname, "dist"),
filename: "[name].js",
};
export const target = "electron-main";
export const module = {
rules: [
{
test: /\.(js|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
};
And webpack.react.config.babel.js:
import { resolve as _resolve } from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
export const resolve = {
extensions: [".tsx", ".ts", ".js"],
mainFields: ["main", "module", "browser"],
};
export const entry = "./src/App.tsx";
export const target = "electron-renderer";
export const devtool = "source-map";
export const module = {
rules: [
{
test: /\.(js|ts|tsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
},
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: "file-loader",
options: {
name: "images/[hash]-[name].[ext]",
},
},
],
},
],
};
export const devServer = {
historyApiFallback: true,
compress: true,
hot: true,
port: 4000,
devMiddleware: {
publicPath: "/",
}
};
export const output = {
path: _resolve(__dirname, "dist"),
filename: "js/[name].js",
};
export const plugins = [new HtmlWebpackPlugin()];
I'm using the latest LTS version of Node (16.13.0) if that's of any help.
The code that's breaking is from a file which I didn't manually generate so I doubt it's of any use but here's jsonp chunk loading (global is undefined):
global["webpackHotUpdatebiomech"] = (chunkId, moreModules, runtime) => {
for(var moduleId in moreModules) {
if(__webpack_require__.o(moreModules, moduleId)) {
currentUpdate[moduleId] = moreModules[moduleId];
if(currentUpdatedModulesList) currentUpdatedModulesList.push(moduleId);
}
}
if(runtime) currentUpdateRuntime.push(runtime);
if(waitingUpdateResolves[chunkId]) {
waitingUpdateResolves[chunkId]();
waitingUpdateResolves[chunkId] = undefined;
}
};
Adding <script>var global = global || window;</script> to your index.html file will resolve the issue. I tried to remove it and am getting the same error you are.
Don't use context isolation ( I agree with the Electron team's rationale for contextIsolation: true, IF you EVER plan to load 3rd party websites or even your own website that has 3rd party javascript running, as they could access your IPC calls ). However if you treat the app as a secure app and never load third party websites or scripts, then it's fine to turn off.
If you still want to go ahead, modify the next.config.js:
if (!isServer) {
config.target = 'electron-renderer';
config.node = {
__dirname: true,
};
}
config.output.globalObject = 'this';

How do I get css-loader and style-loader properly working to allow me to use my CSS file with Webpack?

I am setting up a simple React and Express application using Webpack and I have run into a problem where I am apparently not using my loaders correctly. I have however gone through the docs and I seemingly have them set up right. Does anyone have any idea why the loaders are not being recognized correctly?
Package.Json:
{
"name": "jobhound",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon ./server/server.js",
"build": "webpack --watch",
"test": "jest"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Running-On-Fumes/jobhound.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/Running-On-Fumes/jobhound/issues"
},
"homepage": "https://github.com/Running-On-Fumes/jobhound#readme",
"dependencies": {
"#babel/core": "^7.15.5",
"#babel/plugin-transform-runtime": "^7.15.0",
"#babel/preset-env": "^7.15.6",
"#babel/preset-react": "^7.14.5",
"#testing-library/react": "^12.1.0",
"babel": "^6.23.0",
"babel-loader": "^8.2.2",
"body-parser": "^1.19.0",
"enzyme": "^3.11.0",
"express": "^4.17.1",
"jest": "^27.2.1",
"nodemon": "^2.0.12",
"path": "^0.12.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.3.0",
"webpack": "^5.53.0"
},
"devDependencies": {
"#wojtekmaj/enzyme-adapter-react-17": "^0.6.3",
"css-loader": "^6.3.0",
"style-loader": "^3.3.0",
"webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.2.1"
}
}
I have seemingly set up my webpack config correctly:
webpack.config
const webpack = require('webpack');
const SRC_DIR = path.join(__dirname, 'client', 'src');
const OUT_DIR = path.join(__dirname, 'client', 'dist');
module.exports = {
entry: path.join(SRC_DIR, 'index.js'),
output: {
path: OUT_DIR,
filename: 'bundle.js'
},
module: {
rules: [
{
test:/\.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use: ["style-loader", "css-loader",
]
},
]
},
mode: 'development',
resolve: {
extensions: ['.js', '.jsx']
},
};
I even imported it to my index.js file:
import React from 'react';
import ReactDom from 'react-dom';
import App from './app';
import { BrowserRouter } from 'react-router-dom';
import './css/NavBar.css';
ReactDom.render(
<BrowserRouter>
<App/>
</BrowserRouter>, document.getElementById('App'));
I am just trying to do a simple change in the CSS file to test it out:
.NavBar {
font-weight: bolder;
}
But I get this error:
NavBar.css:1 Uncaught Error: Module parse failed: Unexpected token (1:0)
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
> .NavBar {
| font-weight: bolder;
| }
at eval (NavBar.css:1)
at Object../client/src/css/NavBar.css (bundle.js:18)
at __webpack_require__ (bundle.js:424)
at eval (index.js:6)
at Object../client/src/index.js (bundle.js:73)
at __webpack_require__ (bundle.js:424)
at bundle.js:488
at bundle.js:490
Here is my file tree just in case...
The module.exports.resolve.extensions property in your webpack.config only has .js and .jsx. Try adding .css as well.

Webpack - You may need an appropriate loader

Each time I come back to work with JavaScript, I struggle with webpack and transpilers. I need help here, I am stuck. Webpack is not finding appropriate loader even when specified.
webpack.config.js
const path = require( "path" );
module.exports = {
entry: "./app.js",
output: {
filename: "starmap.js",
path: path.resolve(__dirname, "../asset/js/" )
},
mode : "development",
module : {
rules : [
{
test: /\\.js$/,
exclude: /node_modules/,
loader: "babel-loader",
options: {
presets: [ "#babel/preset-env", "#babel/preset-react" ]
}
}
]
}
}
package.json
{
"name": "editor",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0"
},
"devDependencies": {
"#babel/cli": "^7.12.1",
"#babel/core": "^7.12.3",
"#babel/preset-env": "^7.12.1",
"#babel/preset-react": "^7.12.1",
"#webpack-cli/init": "^1.0.2",
"babel-loader": "^8.1.0",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"css-loader": "^5.0.0",
"style-loader": "^2.0.0",
"terser-webpack-plugin": "^5.0.0",
"webpack": "^5.1.3",
"webpack-cli": "^4.1.0"
}
}
app.js
import React from "react"
import { render } from "react-dom"
class Starmap extends React.Component {
constructor() {
super()
this.state = []
}
render() {
return "Hello world"
}
}
render( <Starmap />, document.getElementById("customizer"))
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
When I run webpack, I get this error:
ERROR in ./app.js 15:8
Module parse failed: Unexpected token (15:8)
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
| }
|
> render( <Starmap />, document.getElementById("_customizer"))
But running npx babel app.js transpiles successfully. Is something wrong with my webpack config, I have watched carefully, everything seems okay.
It seems that your js is not being handled by the babel-loader. I believe the issue is in your test regex
change
test: /\\.js$/,
to
test: /\.js$/,

Appropriate loader error on index.js

I'm stuck on this same error and I need fresh eyes for help.... I'm confused on the "appropriate loader". I was thinking this was from an improper regular expression in the webpack file. I checked the babel docs and this issue for guidance.
This is the error...
ERROR in ./src/index.js
Module parse failed: Unexpected token (6:16)
You may need an appropriate loader to handle this file type.
# multi (webpack)-dev-server/client?http://localhost:8080 ./src
This is my src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './Components/App'
ReactDOM.render(<App />, document.getElementById('root'))
.babelrc
{
"presets": ["env", "react"],
"env": {
"development": {
"plugins": [["react-transform",{
"transforms": [{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}]
}]]
}
}
}
webpack.dev.config.js
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/',
},
module: {
rules: [
{ test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: [path.resolve(__dirname, "src")]
}
],
},
devServer: {
historyApiFallback: true,
inline: true,
hot: true,
},
plugins: [
new HtmlWebpackPlugin({template: 'src/index.html'}),
new webpack.HotModuleReplacementPlugin()
],
}
and my package.json
{
"name": "webpack-starter-kit",
"version": "1.0.0",
"description": "starter files for basic development and production using React, Babel, Webpack",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --progress --mode=development",
"build": "webpack --mode=production"
},
"author": "Kevin Turney",
"license": "ISC",
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-plugin-react-transform": "^3.0.0",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"css-loader": "^0.28.11",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.0.7",
"postcss-loader": "^2.1.2",
"react-transform-hmr": "^1.0.4",
"style-loader": "^0.20.3",
"uglifyjs-webpack-plugin": "^1.2.4",
"webpack": "^4.6.0",
"webpack-cli": "^2.0.15",
"webpack-dev-server": "^3.1.1"
}
}

Webpack ExtractTextPlugin with boostrap-sass

I am using bootstrap sass and extract text-plugin to output the compiled css into a file. It works perfectly if I don't import bootstrap inside my style.scss, but when I import bootstrap webpack can't resolve the font paths. It looks for bootstrap fonts in my src folder instead of the /node_modules/bootstrap-sass/
Module not found: Error: Cannot resolve 'file' or 'directory' ../fonts/bootstrap/glyphicons-halflings-regular.svg in /Users/yasinyaqoobi/Sites/dari-dictionary-api/src/assets/sass
#import "~bootstrap-sass/assets/stylesheets/bootstrap";
package.json
{
"name": "dari-dictionary-api",
"version": "1.0.0",
"description": "Dari Dictionary API built with express.js for the Android App.",
"main": "dist",
"scripts": {
"dev": "nodemon --ignore src/assets -w src --exec \"babel-node src --presets es2015,stage-0\"",
"build": "babel src -s -D -d dist --presets es2015,stage-0",
"start": "node dist",
"prestart": "npm run -s build",
"test": "eslint src",
"watch": "webpack --display-error-details --config webpack.config.js --watch"
},
"repository": {
"type": "git",
"url": ""
},
"author": "Yasin Yaqoobi",
"license": "MIT",
"dependencies": {
"body-parser": "^1.13.3",
"bootstrap-sass": "^3.3.7",
"compression": "^1.5.2",
"cors": "^2.7.1",
"express": "^4.13.3",
"nunjucks": "^3.0.0",
"path": "^0.12.7"
},
"devDependencies": {
"babel-cli": "^6.9.0",
"babel-core": "^6.20.0",
"babel-loader": "^6.2.9",
"babel-plugin-transform-runtime": "^6.15.0",
"babel-polyfill": "^6.20.0",
"babel-preset-es2015": "^6.18.0",
"babel-preset-latest": "^6.16.0",
"babel-preset-stage-0": "^6.5.0",
"babel-runtime": "^6.20.0",
"css-loader": "^0.26.1",
"eslint": "^3.1.1",
"express-winston": "^2.0.0",
"extract-text-webpack-plugin": "^1.0.1",
"file-loader": "^0.9.0",
"node-sass": "^4.0.0",
"nodemon": "^1.9.2",
"sass-loader": "^4.0.2",
"sqlite3": "^3.1.8",
"style-loader": "^0.13.1",
"url-loader": "^0.5.7",
"webpack": "^1.14.0",
"winston": "^2.3.0"
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var extractCSS = new ExtractTextPlugin('public/css/style.css');
module.exports = {
entry: path.resolve(__dirname, 'src/assets/js'),
output: {
filename: 'public/js/index.js',
},
devtool: "source-map",
module: {
loaders: [{
loader: "babel-loader",
// Skip any files outside of your project's `src` directory
exclude: /node_modules/,
// Only run `.js` and `.jsx` files through Babel
test: /\.jsx?$/,
// Options to configure babel with
query: {
plugins: ['transform-runtime'],
presets: ['es2015', 'stage-0'],
}
},
{ test: /\.scss$/i, loader: extractCSS.extract(['css', 'sass']) },
{ test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/
, loader: 'url?limit=100000&name=[name].[ext]'
}
]
},
plugins: [
extractCSS,
new webpack.ProvidePlugin({ // Make jquery available globally
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
],
debug: true,
}

Categories