Debug React in non minified version - javascript

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.

Related

DID-JWT Parse Failed - You may need an additional loader to handle the result of these loaders

I am trying to create a DID (Decentralized ID) using the crypto library in ReactJS 18, like below:
import React from 'react'
import { randomDidKey } from "verite"
import { randomBytes } from "crypto"
const Confirm = ({values}) => {
const issuerDidKey = randomDidKey(randomBytes)
return (
<div>
{issuerDidKey.id}
</div>
)
}
export default Confirm
Whenever I try to run my ReactJS 18.0.0 project using the crypto library I get an error about needing additional loaders.
> react-scripts --openssl-legacy-provider start
ℹ 「wds」: Project is running at http://192.168.0.51/
ℹ 「wds」: webpack output is served from
ℹ 「wds」: Content not from webpack is served from /Users/mabeloza/abja/abja-webapp/public
ℹ 「wds」: 404s will fallback to /
Starting the development server...
Failed to compile.
./node_modules/did-jwt/lib/index.module.js 1724:17
Module parse failed: Unexpected token (1724:17)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| // TODO: should be able to use non base58 keys too
| return key.type === 'X25519KeyAgreementKey2019' && Boolean(key.publicKeyBase58);
> })) ?? [];
| if (!pks.length && !controllerEncrypters.length) throw new Error(`no_suitable_keys: Could not find x25519 key for ${did}`);
| return pks.map(pk => x25519Encrypter(base58ToBytes(pk.publicKeyBase58), pk.id)).concat(...controllerEncrypters);
Below is my package.json file
{
"name": "abja-network-webapp",
"version": "0.1.0",
"private": true,
"keywords": [
"abja"
],
"dependencies": {
"#analytics/google-analytics": "0.2.2",
"#material-ui/core": "4.12.3",
"#material-ui/icons": "4.11.2",
"#material-ui/lab": "4.0.0-alpha.60",
"#passbase/button": "^4.2.4",
"analytics": "0.3.1",
"crypto-browserify": "^3.12.0",
"firebase": "9.1.0",
"formik": "^2.2.9",
"formik-stepper": "^2.0.3",
"history": "4.10.1",
"mailchimp-api-v3": "1.14.0",
"material-ui-phone-number": "^3.0.0",
"query-string": "6.13.8",
"react": "18.0.0",
"react-bootstrap": "^2.2.2",
"react-dom": "18.0.0",
"react-helmet": "6.1.0",
"react-hook-form": "6.15.1",
"react-query": "3.32.1",
"react-router-dom": "5.2.0",
"react-scripts": "4.0.3",
"styled-components": "^5.3.5",
"use-local-storage-state": "9.0.2",
"verite": "^0.0.1",
"yup": "^0.32.11"
},
"scripts": {
"start": "react-scripts --openssl-legacy-provider start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/plugin-proposal-class-properties": "^7.16.7",
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/preset-env": "^7.16.11",
"#babel/preset-react": "^7.16.7",
"babel-loader": "^8.2.4",
"css-loader": "^6.7.1",
"html-webpack-plugin": "^5.5.0",
"style-loader": "^3.3.1",
"webpack": "^5.72.0",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.8.1"
}
}
Below is my .babelrc:
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-proposal-class-properties"
]
}
Below is the webpack.config.js file:
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const port = process.env.PORT || 3000;
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'bundle.[hash].js'
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
localsConvention: 'camelCase',
sourceMap: true
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'public/index.html',
favicon: 'public/favicon.ico'
})
],
devServer: {
host: 'localhost',
port: port,
historyApiFallback: true,
open: true
}
};

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

Changes in node_modules does not reflect to React (possibly bundle.js not getting updated)

I'm using a library in my react application that I want to make a few changes to. I know how to use patch-package so the persistence of the changes will not be a problem, but I can't fiddle with the code for developing purposes because my changes are not reflected when I run react.
Here's an example of the folder structure in the library;
x-library
-dist
--components
---index.js
--bundle.js
When I make changes in index.js, it does not reflect to react. It does so when I make the same change in bundle.js, so I'm guessing index.js gets ignored somehow? I don't know how webpack/bundle.js works very well but from what I understand, bundle.js is a compressed version of the code that the browser uses. Is it that my changes in code does not get compressed again for a new version of bundle.js and uses the old one?
Here's the library's webpack.config.js;
var path = require('path')
module.exports = {
mode: 'production',
entry: './src/index.tsx',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
library: 'Wheel',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.tsx?$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|dist)/,
use: 'ts-loader',
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
},
},
],
},
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
externals: {
react: {
commonjs: 'react',
commonjs2: 'react',
amd: 'React',
root: 'React',
},
'react-dom': {
commonjs: 'react-dom',
commonjs2: 'react-dom',
amd: 'ReactDOM',
root: 'ReactDOM',
},
},
}
And here's the library's package.json;
{
"name": "react-custom-roulette",
"version": "1.1.8",
"description": "Customizable React roulette wheel with spinning animation",
"main": "./dist/bundle.js",
"repository": {
"type": "git",
"url": "https://github.com/effectussoftware/react-custom-roulette"
},
"keywords": [
"react",
"custom",
"roulette",
"spinning",
"wheel",
"fortune",
"prize"
],
"license": "MIT",
"types": "./dist/index.d.ts",
"private": false,
"dependencies": {
"#types/jest": "^25.2.3",
"#types/node": "^14.0.9",
"#types/react": "^16.9.0",
"#types/react-dom": "^16.9.0",
"react-scripts": "^4.0.3"
},
"peerDependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"#testing-library/jest-dom": "^5.9.0",
"#testing-library/react": "^10.0.6",
"#testing-library/user-event": "^11.0.0",
"#typescript-eslint/eslint-plugin": "^4.16.1",
"#typescript-eslint/parser": "^4.16.1",
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "8.1.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-plugin-transform-react-jsx": "^6.24.1",
"babel-preset-env": "^1.7.0",
"css-loader": "^3.5.3",
"eslint": "^7.21.0",
"eslint-config-airbnb-typescript-prettier": "^2.1.1",
"eslint-plugin-react": "^7.22.0",
"husky": "^4.2.5",
"jest-canvas-mock": "^2.2.0",
"prettier": "^2.0.5",
"styled-components": "^5.1.1",
"ts-loader": "8.0.7",
"typescript": "^4.2.2",
"url-loader": "^4.1.0",
"webpack": "4.44.2",
"webpack-cli": "^3.3.11",
"webpack-dev-server": "3.11.1"
},
"scripts": {
"start-server": "react-scripts start",
"start": "webpack --watch",
"build": "webpack && tsc && cp -R ./src/assets ./dist",
"test": "react-scripts test",
"coverage": "CI=true npm test -- --env=jsdom --coverage",
"eject": "react-scripts eject",
"format": "prettier --write src/**/*.{js,ts,tsx}",
"lint": "eslint src/**/*.{js,ts,tsx}",
"link-react": "cd example/node_modules/react && npm link && cd ../react-dom && npm link && cd ../../.. && npm link react react-dom"
},
"husky": {
"hooks": {
"pre-commit": "yarn format && yarn lint"
}
},
"jest": {
"coveragePathIgnorePatterns": [
"src/serviceWorker.ts"
]
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

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.

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