Updating Electron issue: Uncaught ReferenceError: global is not defined - javascript

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';

Related

Debug React in non minified version

We have a rather large React project.
Currently when we try to debug it from browser like Chrome, it looks like the following.
!function(){var r,n,e=(n={}
,__webpack_require__.m=r=[function(e,t)
{e.exports=PropTypes},function(e,t)
{e.exports=React},function(e,t,r)
{"use strict";function _typeof(e)
Now this is just part of it and there are 1000s and 1000s of lines of this.
When I try to place breakpoints to debug, I end up with minified version like:
var a = b.l - c.m
Find it extremely unreadable and hard to determine which part of the code it is pointing to.
Is there a way, like a setting in package.json maybe.
Where I can set it such that when I am performing debug work, don't show minified version.
Instead show me the es6 code I have written.
I use Webstorm and somehow, it is so slow when I debug it from there and the breakpoint doesn't always hit even though I am clearly passing the breakpoint.
Thus very unreliable.
Appreciate any help/advice. How to effectively debug a React project?
Is there a way I could add settings to not minify during debug? (localhost and production)
-- UPDATE --
package.json
{
"name": "myproj",
"version": "1.00.0",
"license": "SEE LICENSE IN LICENSE",
"scripts": {
"start": "npm run build && one-run --env domain.com",
"prebuild": "npm run clean",
"build": "rimraf build && bundle-shop-app --clientConfig webpack/client.config.js --serverConfig webpack/server.config.js",
"clean": "rimraf build",
"lint": "eslint --ignore-path .eslintignore --ext js,jsx,snap,md .",
"prepare": "npm run build",
"pretest:browser": "npm run build",
"test:unit": "jest --testPathIgnorePatterns browser a11y",
"test:a11y": "jest a11y --collectCoverage false",
"test": "npm run test:unit",
"posttest": "npm run lint",
"watch:test": "npm run test:unit -- --watch",
"watch:build": "npm run build -- --watch",
"githook:pre-commit": "npm run test",
"githook:commit-msg": "commit-msg"
},
"deploy": {
"from": "storybook-static",
"to": "static",
},
"one": {
"runner": {
"module": [
"."
],
"envVars": {
"KEY": "root"
}
},
"risk": {
"level": "low"
}
},
"jest": {
"preset": "jest-preset-react",
"setupFiles": [
"./test-setup.js"
]
},
"dependencies": {
"classnames": "2.2.6",
"css-loader": "2.1.1",
"focus-visible": "^5.0.2",
"immutable": "^3.7.6",
"lodash": "^4.17.20",
"moment": "^2.29.1",
"prop-types": "^15.7.2",
"react": "^16.14.0",
"react-helmet-async": "^1.0.4",
"react-intl": "^2.2.3",
"react-redux": "^7.0.0",
"react-router": "^3.0.0",
"react-swipeable": "5.5.1",
"redux": "^4.0.0",
"reselect": "^4.0.0",
"style-loader": "^2.0.0"
},
"devDependencies": {
"#babel/polyfill": "^7.4.4",
"babel-preset-amex": "^3.0.0",
"concurrently": "^6.0.0",
"enzyme": "^3.3.0",
"enzyme-to-json": "^3.3.0",
"eslint": "^6.0.0",
"eslint-config-amex": "^11.0.0",
"githook-scripts": "^1.0.1",
"jest": "^24.0.0",
"jest-image-snapshot": "^4.0.0",
"markdown-spellcheck": "^1.3.1",
"react-dom": "^16.14.0",
"react-test-renderer": "^16.14.0",
"underscore": "^1.9.1"
},
"publishConfig": {
"registry": ""
}
}
These are 3 files all inside webpack folder.
base.config.js
const oneMegabyte = 10000000;
module.exports = {
resolve: {
symlinks: false,
},
performance: {
maxEntrypointSize: oneMegabyte,
maxAssetSize: oneMegabyte,
},
};
client.config.js
const path = require('path');
const { cssLoader, sassLoader } = require('domain-cli/webpack/configs');
const base = require('./base.config');
const { name } = require('../package.json');
module.exports = {
...base,
module: {
rules: [
{
test: /\.s?css$/,
include: [
path.join(__dirname, '../src'),
path.join(__dirname, '../node_modules'),
],
oneOf: [
{
resource: /domain-components/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
sassLoader(),
],
},
{
use: [
{ loader: 'style-loader' },
cssLoader({ name }),
sassLoader(),
],
},
],
},
],
},
};
server.config.js
const path = require('path');
const { cssLoader, sassLoader } = require('domain-cli/webpack/configs');
const base = require('./base.config');
const { name } = require('../package.json');
module.exports = {
...base,
module: {
rules: [
{
test: /\.s?css$/,
include: [
path.join(__dirname, '../src'),
path.join(__dirname, '../node_modules'),
],
oneOf: [
{
resource: /domain-components/,
use: [
{
loader: 'bundler/webpack/ssr-css-loader', options: { name },
},
{ loader: 'css-loader' },
sassLoader(),
],
},
{
use: [
{
loader: 'bundler/webpack/ssr-css-loader', options: { name },
},
cssLoader({ name }),
sassLoader(),
],
},
],
},
],
},
};
You need to enable sourcemaps in your webpack config in development.
Source Maps are the files which create a mapping between your source(original) code and your generated code. In other words, a line in your generated code is representing which line of your source code is determined by source maps.

Webpack throws error when trying to build JSX

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.

Importing and using component from custom React Component Library results in Invariant Violation: Invalid hook call

My work is making a React UI Kit/Component Library to be used internally for our products. Everything is working fine while developing and displaying on Storybook.
While testing the library in a generic project out-of-the-box from create-react-app, importing and implementing the components made without React Hooks are alright, but soon as we use the ones made with Hooks - the Invalid Hook Call error shows: https://reactjs.org/warnings/invalid-hook-call-warning.html
Have tried everything listed there(and read and tried the github thread solutions linked on the page), and the component simply used useRef() and nothing else so we know no rules were broken, React and React-dom versions are up to date, and running npm ls react and npm ls react-dom in the project results in react#16.10.2 and react-dom#16.10.2 and nothing else... So it doesn't seem like we have multiple React's?
Any help would be much appreciated!!
This is the UI Kit's package.json
{
"name": "react-ui-kit",
"version": "0.0.15",
"description": "UI Kit",
"main": "dist/index",
"module": "dist/index",
"typings": "dist/index",
"jest": {
"setupFilesAfterEnv": [
"<rootDir>/setupTests.js"
],
"coverageReporters": [
"json-summary",
"text",
"lcov"
]
},
"scripts": {
"test": "jest --coverage",
"test:badges": "npm run test && jest-coverage-badges input './coverage/coverage-summary.json' output './badges'",
"test-update": "jest --updateSnapshot",
"lint:css": "stylelint './src/**/*.js'",
"storybook": "start-storybook -p 6006",
"build-storybook": "build-storybook -c .storybook -o .out",
"generate": "plop --plopfile ./.plop/plop.config.js",
"build": "webpack --mode production",
"prepare": "npm run build",
"prepublishOnly": "npm run test:badges",
"storybook-docs": "build-storybook --docs",
"todo": "leasot './src/**/*.js'",
"todo-ci": "leasot -x --reporter markdown './src/**/*.js' > TODO.md"
},
"license": "ISC",
"peerDependencies": {
"prop-types": "^15.7.2",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"recharts": "^1.7.1",
"styled-components": "^4.3.2",
"styled-normalize": "^8.0.6"
},
"devDependencies": {
"#babel/cli": "^7.6.0",
"#babel/core": "^7.6.0",
"#babel/plugin-proposal-class-properties": "^7.5.5",
"#babel/preset-env": "^7.6.0",
"#babel/preset-react": "^7.0.0",
"#storybook/addon-actions": "^5.2.1",
"#storybook/addon-docs": "^5.2.1",
"#storybook/addon-info": "^5.2.1",
"#storybook/addon-knobs": "^5.2.1",
"#storybook/addon-links": "^5.2.1",
"#storybook/addon-viewport": "^5.2.1",
"#storybook/addons": "^5.2.1",
"#storybook/react": "^5.2.1",
"babel-eslint": "^10.0.3",
"babel-jest": "^24.9.0",
"babel-loader": "^8.0.6",
"babel-plugin-styled-components": "^1.10.6",
"eslint": "^6.5.1",
"eslint-plugin-react": "^7.15.0",
"eslint-plugin-react-hooks": "^2.1.1",
"jest": "^24.9.0",
"jest-coverage-badges": "^1.1.2",
"jest-styled-components": "^6.3.3",
"leasot": "^8.2.0",
"plop": "^2.4.0",
"polished": "^3.4.1",
"prop-types": "^15.7.2",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-test-renderer": "^16.9.0",
"recharts": "^1.7.1",
"storybook-styled-components": "github:merishas/storybook-styled-components",
"styled-components": "^4.4.0",
"styled-normalize": "^8.0.6",
"stylelint": "^10.1.0",
"stylelint-config-recommended": "^2.2.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.8.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9"
},
"files": [
"dist"
],
}
The UI Kit's webpack.config.js
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
path: path.resolve('dist'),
filename: 'index.js',
libraryTarget: 'commonjs2',
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: 'babel-loader',
},
{
test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
limit: 10000,
mimetype: 'application/font-woff',
},
},
],
},
],
},
resolve: {
alias: {
components: path.resolve(__dirname, 'src/components/'),
utils: path.resolve(__dirname, 'src/utils/'),
themes: path.resolve(__dirname, 'src/themes/'),
},
extensions: ['.js', '.jsx'],
},
devtool: false,
};
How components are imported and implemented in project:
import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { FieldLabel, Button } from "react-ui-kit";
function App() {
return (
<div className="App">
<FieldLabel>THIS IS THE ONE USING the useRef Hook</FieldLabel>
<Button>This component is totally fine without FieldLabel, this isn't using Hooks</Button>
</div>
);
}
export default App;
Looking at the webpack config, I could see that, UI kit is getting bundled with react included which might be causing the issue.
To avoid this you could use webpack externals.
https://webpack.js.org/configuration/externals/
The externals configuration option provides a way of excluding
dependencies from the output bundles. Instead, the created bundle
relies on that dependency to be present in the consumer's environment.
This feature is typically most useful to library developers, however
there are a variety of applications for it.
So you could update UI Kit webpack config to not include react and the peerDependencies should take care of the dependency handling for any consumers of the library.
Updated webpack.config
const path = require("path");
module.exports = {
mode: "production",
entry: "./src/index.js",
output: {
path: path.resolve("dist"),
filename: "index.js",
libraryTarget: "commonjs2"
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: "babel-loader"
},
{
test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
use: [
{
loader: "file-loader",
options: {
name: "[name].[ext]",
limit: 10000,
mimetype: "application/font-woff"
}
}
]
}
]
},
resolve: {
alias: {
components: path.resolve(__dirname, "src/components/"),
utils: path.resolve(__dirname, "src/utils/"),
themes: path.resolve(__dirname, "src/themes/")
},
extensions: [".js", ".jsx"]
},
externals: {
// Use external version of React
react: "react"
},
devtool: false
};
I have published a test package to confirm this (react-ui-kit-dontuse).
Demo links
v0.0.21(Without webpack externals)
https://stackblitz.com/edit/react-xyjgep
v0.0.23(With webpack externals)
https://stackblitz.com/edit/react-ihnmrl
Source code of test package: https://github.com/nithinthampi/react-ui-lib-test
Hope this helps!

Error when styling React components imported from index file, but not when importing directly from component file

Newbie here, so apologies in advance if I am overlooking something obvious or missed a duplicate posting (and also for not posting directly on styled-components, apparently I need a rep for that...) .
The closest I found to my problem was in this resolved issue, at the bottom of the thread:
https://github.com/styled-components/styled-components/issues/213
The guy had a very similar problem, but the solution was brief and Typescript specific.
BACKGROUND: I have an index file that imports my components from all over, and exports them under a webpack alias. Whenever I need to import elsewhere I just declare:
import { MyComponentA, MyComponentB, MyComponentC } from 'components';
I recently started incorporating styled-components into my project and have been getting an error like the following when I try to style components imported in this way:
Error: Cannot create styled-component for component: undefined._____________styled-components.browser.esm.js:233
at new StyledComponentsError (/home/jhillert/Dropbox/Projects/TimeLockr/node_modules/styled-components/dist/styled-components.browser.esm.js:233:59)
at constructWithOptions (/home/jhillert/Dropbox/Projects/TimeLockr/node_modules/styled-components/dist/styled-components.browser.esm.js:1355:12)
at styled (/home/jhillert/Dropbox/Projects/TimeLockr/node_modules/styled-components/dist/styled-components.browser.esm.js:2293:11)
at Module.eval (/home/jhillert/Dropbox/Projects/TimeLockr/src/components/card-area/CardArea.jsx:111:91)
at eval (/home/jhillert/Dropbox/Projects/TimeLockr/src/components/card-area/CardArea.jsx:133:31)
at Module../src/components/card-area/CardArea.jsx (http://localhost:8080/bundle.js:9343:1)
at __webpack_require__ (http://localhost:8080/bundle.js:724:30)
at fn (http://localhost:8080/bundle.js:101:20)
at eval (/home/jhillert/Dropbox/Projects/TimeLockr/src/indexes/components.jsx:17:89)
at Module../src/indexes/components.jsx (http://localhost:8080/bundle.js:9619:1)
If I import the component directly from the source file I do not get the error. It only happens when I try to pass components imported from the index file into the styled() method, and also when I try to use the CSS prop to add inline styling.
For some reason the error does not occur with all components imported in this way, and also I have made changes to my code that suddenly cause the index import to trigger the error. I really like having a central index file, so a fix would be greatly appreciated.
Example where css prop causes error:
*Project config below.
Index File looks like this (components.jsx):
export { default as ActionBar } from '../components/action-bar/ActionBar';
export { default as AuthForm } from '../components/auth/AuthForm';
export { default as AuthModal } from '../components/auth/AuthModal';
export { default as AuthTabs } from '../components/auth/AuthTabs';
export { default as Box } from '../components/box/Box';
/*==============================================================*/
//CardArea.js
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import {
CardColumn ◀◀◀—————————————— DOES PRODUCE ERROR
LockedEntryCard,
ReleasedEntryCard,
} from 'components';
import CardColumn from '../card-column/CardColumn' ◀◀◀——————— DOES NOT
const S = {};
S.CardArea = styled.div` ◀◀◀————— NOT IMPORTED, NOT A PROBLEM
/* ommitted */ BUT WOULD CAUSE SAME ERROR
`; IF IMPORTED.
const CardArea = ({ entries, refresh }) => {
const { locked, released } = entries;
const hasLockedChildren = !!(locked.length);
const hasReleasedChildren = !!(released.length);
const [showLocked, updateShowLocked] = useState(false);
const [showReleased, updateShowReleased] = useState(false);
useEffect(() => {
updateShowLocked(true);
updateShowReleased(true);
},
[]);
return (
<S.CardArea>
{(hasReleasedChildren && showReleased)
&& (
<CardColumn
id='card-column-released-entries'
css=' ◀◀◀ TRIGGERS THE ERROR
margin-left = 2rem; ◀◀◀ TRIGGERS THE ERROR
margin-right = 1rem; ◀◀◀ TRIGGERS THE ERROR
' ◀◀◀ TRIGGERS THE ERROR
heading='Unlocked'
Card={ReleasedEntryCard}
/* ommitted */
CardArea.propTypes = {
/* ommitted */
};
export default CardArea;
=================================================================
Webpack configuration (webpack.config.js):
Aliases are towards the bottom.
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const path = require('path');
const config = {
entry: './src/index.jsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.jsx?$/,
include: /node_modules/,
use: ['react-hot-loader/webpack'],
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader/locals',
],
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
'less-loader',
],
},
{
test: /\.png$/,
use: [
{
loader: 'url-loader',
options: {
mimetype: 'image/png',
},
},
],
},
],
},
node: {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty',
},
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
],
plugins: [
new CopyWebpackPlugin([
// relative path is from src
{ from: './static/favicon.ico' }, // <- your path to favicon
]),
new Dotenv({
systemvars: true,
}),
],
devServer: {
contentBase: './dist',
},
resolve: {
extensions: ['.js', '.jsx', '.css'],
alias: {
components: path.resolve(__dirname, 'src/indexes/components.jsx'),
contexts: path.resolve(__dirname, 'src/indexes/contexts.jsx'),
theme: path.resolve(__dirname, 'src/indexes/theme.jsx'),
utilities: path.resolve(__dirname, 'src/indexes/utilities.jsx'),
},
},
};
module.exports = config;
Babel Config (.bablerc):
{
presets: [
[
'#babel/preset-env',
{
modules: false
}
],
'#babel/preset-react'
],
plugins: [
'react-hot-loader/babel',
'#babel/plugin-proposal-class-properties',
'#babel/plugin-transform-react-jsx-source',
[
'babel-plugin-styled-components',
{
"ssr": false
}
],
]
}
Dependencies (Package.json)
{
"name": "timelockr",
"version": "1.0.0",
"description": "Making information inaccessible.",
"main": "index.js",
"keywords": [],
"author": "",
"license": "ISC",
"repository": {
"type": "git",
"url": "https://github.com/jehillert/Keep-Away"
},
"scripts": {
"clean": "rm dist/bundle.js",
"build-dev": "webpack -d --mode development",
"build-prod": "webpack -p --mode production",
"dev-server": "nodemon --ignore node_modules --inspect server",
"start": "webpack-dev-server --host 0.0.0.0 --hot --mode development",
"start:dev": "nodenv -f .",
"lint:css": "stylelint './src/**/*.js'"
},
"dependencies": {
"#date-io/date-fns": "^1.1.0",
"#date-io/moment": "^1.1.0",
"#material-ui/core": "^3.9.3",
"#material-ui/icons": "^3.0.2",
"#material-ui/styles": "^4.0.0-alpha.4",
"#material-ui/system": "^3.0.0-alpha.2",
"ajv": "^6.10.0",
"axios": "^0.18.0",
"bluebird": "^3.5.3",
"body-parser": "^1.18.3",
"bootstrap": "^4.3.1",
"classnames": "^2.2.6",
"cors": "^2.8.5",
"date-fns": "^2.0.0-alpha.27",
"debug": "^4.1.1",
"dotenv-webpack": "^1.7.0",
"express": "^4.16.4",
"express-mysql-session": "^2.1.0",
"express-session": "^1.15.6",
"jquery": "^3.3.1",
"less": "^3.9.0",
"material-ui-pickers": "^2.2.4",
"moment": "^2.24.0",
"mysql": "^2.16.0",
"notistack": "^0.6.1",
"pbkdf2-password": "^1.2.1",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-bootstrap": "^1.0.0-beta.6",
"react-copy-to-clipboard": "^5.0.1",
"react-dom": "^16.8.6",
"react-hot-loader": "^4.8.2",
"react-router-dom": "^5.0.0",
"react-transition-group": "^2.7.1",
"styled-components": "^4.2.0",
"typeface-roboto": "0.0.54"
},
"devDependencies": {
"#babel/core": "^7.4.0",
"#babel/plugin-proposal-class-properties": "^7.4.0",
"#babel/preset-env": "^7.4.2",
"#babel/preset-react": "^7.0.0",
"async": "^2.6.2",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.5",
"babel-plugin-styled-components": "^1.10.0",
"babel-plugin-transform-react-jsx-source": "^6.22.0",
"copy-webpack-plugin": "^5.0.2",
"css-loader": "^1.0.0",
"eslint": "^5.16.0",
"eslint-config-airbnb": "^17.1.0",
"eslint-import-resolver-webpack": "^0.11.0",
"eslint-plugin-import": "^2.16.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-react": "^7.12.4",
"eslint-plugin-react-hooks": "^1.6.0",
"eslint_d": "^7.3.0",
"faker": "^4.1.0",
"less-loader": "^4.1.0",
"node-cmd": "^3.0.0",
"nodemon": "^1.18.10",
"style-loader": "^0.23.1",
"stylelint": "^9.10.1",
"stylelint-config-recommended": "^2.1.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.6.0",
"url-loader": "^1.1.2",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}
}
The following github issues from the arc repo seem to describe problems similar to the one you are having here: #339, #130. The last issue specifically has this comment which suggests a potential solution. By styling in the following manner in most cases the problem is said to be resolved:
const StyledCComponent = styled(props => <CComponent {...props} />)``
The root underlying cause seem to be a circular dependency issue. By wrapping the component in a function the dependency is evaluated at runtime.

Babel isn't transpiling ES6 to ES5

I'm desperately trying to get my Webpack config file to transpile ES6 into ES5, but for some reason it doesn't seem to work. I'm still getting the 'const' variable, arrow functions and spread operators in my exported js code. I've attached my webpack config file and my package.json file - any help would be really appreciated.
Package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build:dev": "cross-env NODE_ENV=development webpack --mode development",
"build:prod": "cross-env NODE_ENV=production webpack --mode production",
"start": "webpack-dev-server --port 9000 --mode development"
},
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.7.7",
"#babel/plugin-transform-runtime": "^7.8.3",
"#babel/preset-env": "^7.7.7",
"#babel/runtime": "^7.8.4",
"autoprefixer": "^9.7.3",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"copy-webpack-plugin": "^5.1.1",
"cross-env": "^6.0.3",
"css-loader": "^3.4.0",
"file-loader": "^5.0.2",
"html-webpack-plugin": "^3.2.0",
"image-webpack-loader": "^6.0.0",
"imagemin-webpack-plugin": "^2.4.2",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.0",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"postcss-loader": "^3.0.0",
"sass-loader": "^8.0.0",
"typescript": "^3.7.4",
"uglifyjs-webpack-plugin": "^2.2.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1",
"webpack-merge": "^4.2.2"
},
"dependencies": {
"#babel/polyfill": "^7.8.3",
"#glidejs/glide": "^3.4.1",
"aos": "^3.0.0-beta.6",
"axios": "^0.19.2",
"core-js": "2",
"jquery": "^3.4.1",
"lodash": "^4.17.15",
"query-string": "5.1.1",
"scrollbooster": "^2.1.0",
"simple-parallax-js": "^5.2.0",
"smooth-scrollbar": "^8.5.1",
"tippy.js": "^5.1.4"
}
}
Webpack config:
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const data = require('../pageinfo.json');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
entry: ['#babel/polyfill','./src/scripts/index.js'],
output: {
path: path.resolve(__dirname, '../dist'),
filename: '[name].[chunkhash].js'
},
module: {
rules: [{
test: [/.css$|.scss$/],
use: [MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
},
{
test: /\.(jpe?g|png|svg|gif)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/images'
}
}]
},
{
test: /\.m?js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: [["#babel/preset-env", { "useBuiltIns": "usage" }]],
plugins: [
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
}
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'assets/fonts'
}
}]
}
]
},
resolve: {
extensions: ['.js']
},
plugins: [
new MiniCssExtractPlugin({
filename: 'style.css'
}),
new CopyWebpackPlugin([{
from: './src/assets/images',
to: 'assets/images'
}]),
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'style.[chunkhash].css'
})
]
};
Go to your package.json file. The babel command takes two arguments: the path to your ES6 code and a path to where you want your ES5 code to go.
If you have all your JavaScript code housed in a directory, then you can add the -d flag to the command to tell Babel for look for directories instead of files. For my example, I have my JavaScript code in my src directory but want my ES5 code to be put in a build directory.
// package.json
...
"scripts": {
"build": "babel src -d build",
},
...
Then just run the Babel command
With your .babelrc file created and your build command ready, just run it in your command line.
npm run build

Categories