Cant find what causes the error when import component class - node.js

Im getting an error : unexpected token when importing a component-class while within another component class.
Im new to react, webpack and still learning javascript nodejs callbacks hooks, Im reading and search for best practices regardig nodejs and react on how to setup my dev-environment on Ubuntu.
A lot of trial and error to figure out whats going on behind the scene.
Im able to connect to my single page if I dont add as soon as I add import it raises an error.
// main.jsx
import React from "react";
import ReactDOM from "react-dom";
import App from './App.jsx';
ReactDOM.render( <App /> , document.getElementById('root'));
// App.jsx
import React from 'react';
import {SubmitButton} from './components/SubmitButton';
export default class App extends React.Component {
render(){
return(<div><h1>Hi, I am a header!</h1></div>);
}
}
// SubmitButton.jsx
import React , {Component} from 'react';
export class SubmitButton extends Component{
constructor() {
super();
}
render() {
return(<div>Swing</div>);
}
}
// $npm run start ... webpack.config.js :
"scripts": {
"start": "webpack-dev-server --display-error-details --config webpack.config.js --hot --mode development",
"build" : "webpack"
}
// ERROR
ERROR in ./src/components/SubmitButton/SubmitButton.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /appdevops/graphCRMcli/src/components/SubmitButton/SubmitButton.jsx: Unexpected token (8:9)
6 | }
7 | render() {
> 8 | return(<div>
| ^
9 | <SubmitButton>Swing</SubmitButton>
10 | </div>
11 | );
at Parser.raise
///package.json file
{
"name": "MyClient",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"start": "webpack-dev-server --display-error-details --config webpack.config.js --hot --mode development",
"build" : "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.6",
"cross-spawn": "^7.0.0",
"css-loader": "^3.2.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"react": "^16.10.1",
"react-dom": "^16.10.1",
"style-loader": "^1.0.0",
"webpack": "^4.41.0",
"webpack-cli": "^3.3.9",
"webpack-dev-middleware": "^3.7.2",
"webpack-dev-server": "^3.8.1"
},
"dependencies": {}
}
// .babelrc
{
"presets": ["#babel/preset-env", "#babel/preset-react"]
}
// webpack.config.js
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// HtmlWebpackPlugin is used to inject our created bundles into this html file so // we need to create it.
const HtmlWebpackPluginConfig = new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body',
});
module.exports = {
mode : 'development',
entry: {
app: ['./src/main.jsx'],
vendor: ['react', 'react-dom']
},
output: {
path: '/appdevops/graphCRMcli/dist',
libraryTarget: 'umd',
filename: '[name].js'
},
devServer: {
host : '0.0.0.0',
compress: true,
port: 3000
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
HtmlWebpackPluginConfig
],
};

I solved it by adjusting webpack.config.js and :
removing .babelrc
adding contents of .babelrc to webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env", "#babel/preset-react" ]
}
}
}
]
}

Related

How to configure webpack 5 to output ts files in dist folder from src folder?

I am using webpack 5 with typescript and a node.js app.
My folder structure is
src/
server.ts
mymodule.ts
public/
index.html
main.ts
utils.ts
but I want to output the compiled files as
dist/
server.js
mymodule.js
public/
index.html
bundle.js
This is my package.json
{
"name": "to-do",
"version": "1.0.0",
"description": "An application for to do list",
"main": "server.js",
"type": "module",
"scripts": {
"start": "node server.js",
"debug": "node --inspect server.js",
"build": "webpack",
"serve": "webpack serve"
},
"license": "MIT",
"dependencies": {
"express": "^4.18.1",
"filenamify": "^5.1.1",
"html-webpack-plugin": "^5.5.0",
"http": "^0.0.1-security",
"ts-loader": "^9.3.1",
"typescript": "^4.7.4",
"webpack": "^5.73.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3"
},
"keywords": [
"todo"
],
"devDependencies": {
"#types/express": "^4.17.13",
"#types/node": "^18.0.6"
}
}
This is my webpack configuration
import path from 'path';
import { fileURLToPath } from 'url';
import HtmlWebpackPlugin from 'html-webpack-plugin';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export default {
entry: {
bundle : './src/public/main.ts'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
target:'node',
resolve: {
extensions: ['.ts', '.js'],
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/public/index.html',
scriptLoading:"module"
})
],
output: {
filename: '[name].js',
path: path.join(__dirname, 'dist'),
clean: true
},
mode: 'development',
devtool: 'inline-source-map',
devServer: {
hot: true,
static: {
directory: './dist',
},
compress: true,
port: 3002,
headers: {
'Cross-Origin-Embedder-Policy': 'require-corp',
'Cross-Origin-Opener-Policy': 'same-origin'
}
},
stats: {
errorDetails:true
}
};
I get an error about server.js can't be resolved, since I assume it looks at the main from package.json.
ERROR in ./src/public/main.ts 3:0-36
Module not found: Error: Can't resolve './server.js' in 'C:\Users\Desktop\4\src\public'
resolve './server.js' in 'C:\Users\Desktop\4\src\public'
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public)
using description file: C:\Users\Desktop\4\package.json (relative path: ./src/public/server.js)
no extension
How can I resolve this?

Babel is not transpiling nodejs modules

I've created a few nodejs modules and trying to bundle them using webpack, after been transpiled using babel. But it seems babel is not transpiling modules.
Following is my project structure:
> config
> connection
> controllers
> models
> node_modules
> routes
.babelrc
.env
.gitignore
chalk.console.js
package-lock.json
package.json
Procfile
index-bundle.js
index.js
webpack.config.js
Following is the package.json
{
"name": "index-service",
"version": "0.1.0",
"main": "index.js",
"scripts": {
"dev-run": "webpack && node index-bundle.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
"dependencies": {
"#babel/core": "7.11.6",
"#babel/node": "7.10.5",
"#babel/preset-env": "7.11.5",
"babel-loader": "8.1.0",
"body-parser": "1.19.0",
"core-js": "3.6.5",
"dotenv": "8.2.0",
"express": "4.17.1",
"pg": "8.4.0",
"pg-hstore": "2.3.3",
"regenerator-runtime": "0.13.7",
"sequelize": "6.3.5",
"webpack": "4.44.2",
"webpack-node-externals": "2.5.2",
},
"devDependencies": {
"chalk": "^4.1.0",
"nodemon": "^2.0.4",
"webpack-cli": "^3.3.12"
}
}
Following is the index.js
require('core-js/stable');
require('dotenv').config();
require('regenerator-runtime/runtime');
const chalk = require('./chalk.console');
const bodyParser = require('body-parser');
const express = require('express');
....
app.listen(PORT, () => {
console.log(chalk.info(`Service running on port ${PORT}`));
});
Following is the webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: "development",
target: 'node',
externals: [nodeExternals()],
entry: './index.js',
output: {
path: __dirname,
filename: 'index-bundle.js'
},
module: {
rules: [
{
test: /.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
}
]
}
};
Following is the .babelrc file:
{
"presets": [
"#babel/preset-env"
]
}
Following is the chalk.console.js:
const chalk = require('chalk');
const error = chalk.redBright;
const success = chalk.greenBright;
const warning = chalk.hex('#ff3d00');
const info = chalk.yellowBright;
//This is where the error is occuring
export {
error,
success,
warning,
info
};
So, whenever I run npm run dev-run
I get the following error
D:\NodeJS Services\Index\chalk.console.js:8
export {
^^^^^^
SyntaxError: Unexpected token 'export'
The exact same project structure and same .babelrc, webpack.config.js, and package.json dependencies are working in my another project, but not this one. I wonder where did I go wrong

How to build (Webpack) the Node Js project using PUG Engine?

I am stuck to build the node js project using webpack and I am using pug engine for front end.
My Project Structure:
bin
controller
- csv.controller.js
public
- stylesheets
- javascript
- images
routes
- csv.route.js
- index.route.js
views
- layouts
-- layout.pug
-index.pug
app.js
Package.json File
{
"name": "csv",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "webpack --mode=production",
"build:dev": "webpack --mode=development",
"start":"nodemon ./app.js",
"start:dev": "webpack-dev-server --mode=development"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "^1.7.4",
"cookie-parser": "~1.4.4",
"csv-parser": "^2.3.1",
"csv-writer": "^1.5.0",
"debug": "~2.6.9",
"express": "^4.17.1",
"express-fileupload": "^1.1.6-alpha.5",
"fast-csv": "^3.4.0",
"http-errors": "~1.6.3",
"morgan": "^1.9.1",
"multer": "^1.4.2",
"npm-check-updates": "^3.1.23",
"request": "^2.88.0"
},
"devDependencies": {
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.2.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"pug": "^2.0.4",
"pug-loader": "^2.4.0",
"style-loader": "^1.0.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.1",
"webpack-merge": "^4.2.2"
}
}
Actually what I want, after build, A dist folder contain a build.js or whatever its name and all public folder assets in the same directory. I tried with some below codes to build the project.
Webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
entry: {
app: "./app.js"
},
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js"
},
devServer: {
port: 3000
},
plugins: [
new HtmlWebpackPlugin({
template: "./views/index.pug"
})
],
module: {
rules: [
{
test: /\.pug$/,
use: ["pug-loader"]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: [/.js$/],
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
}
if (argv.mode === "production") {
}
return config;
};
I know this question is old, but just in case somebody is looking for an answer.
You need another Webpack config for app.js, which is express entry point.
Call it webpack.server.js or webpack.server.config.js or whatever convenient. Make sure to include webpack-node-externals:
https://www.npmjs.com/package/webpack-node-externals
It may look something like this:
//webpack.server.js
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
return ({
entry: {
app: ./src/server/app.js,
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js',
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
});
};
Also use webpack-dev-middleware in your app.js.
See the below link:
https://webpack.js.org/guides/development/
In package.json include a script that looks something like this:
"server:dev": "webpack --config webpack.config.js && webpack --mode development --config webpack.server.js && node ./dist/app.js",
In your webpack.config.js make the entry point the js file that imports your front-end assets..
That is your stylesheets and any other js codes..
Not sure what css framework you are using.
But, I am using tailwindcss and I have a js entry point file that imports tailwindcss and my other js codes.
So essentially you may need two webpack config files one for the front-end and one for the express server.
Hope I am making sense.

webpack 4 react build causes token error, but run start works

After a build with webpack I am getting the Uncaught SyntaxError: Unexpected token error. I am able to run start and it will load that way. So I know this must be a problem with the output, or so I would imagine.
The index.html is generating properly, as is the bundle.js. I have that as a path on my index.html file. I am using webpack 4 and have the following webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports ={
entry: './src/index.js',
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
rules: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
},
devServer: {
host: 'localhost',
port: '8080'
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
]
}
My .babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties"
]
}
Index.html
<!DOCTYPE html>
<html>
<head>
<title>Expensify</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="src"></div>
<script type="text/javascript" src="bundle.js"></script></body>
</body>
</html>
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { createStore, compose, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import reducer from './store/reducers/auth';
const composeEnhances = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore(reducer, composeEnhances(
applyMiddleware(thunk)
));
const app = (
<Provider store={store}>
<App />
</Provider>
)
ReactDOM.render(app, document.getElementById('src'));
Packages.json
{
"name": "reactboilerplate",
"version": "1.0.0",
"description": "React Webpack Redux Babel Boilerplate",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack --mode production"
},
"author": "Thomas Baric",
"license": "ISC",
"dependencies": {
"#babel/core": "^7.2.2",
"#babel/plugin-proposal-class-properties": "^7.3.0",
"#babel/preset-env": "^7.3.1",
"#babel/preset-react": "^7.0.0",
"#material-ui/core": "^3.9.2",
"#material-ui/icons": "^3.0.2",
"axios": "^0.18.0",
"babel-cli": "^6.26.0",
"babel-loader": "^8.0.5",
"babel-plugin-lodash": "^3.3.4",
"babel-plugin-react-transform": "^3.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"dateformat": "^3.0.3",
"g": "^2.0.1",
"help": "^3.0.2",
"react": "^16.8.1",
"react-dom": "^16.8.1",
"react-redux": "^6.0.0",
"react-router-dom": "^4.3.1",
"react-slick": "^0.23.2",
"redux": "^4.0.1",
"redux-thunk": "^2.3.0",
"webpack": "^4.29.3",
"webpack-cli": "^3.2.3"
},
"devDependencies": {
"html-webpack-plugin": "^3.2.0",
"webpack-dev-server": "^3.1.14"
}
}
For those wondering this was a backend Django problem regarding static files. Here is my working webpack and babel. This does work on heroku. https://djreactboilertest.herokuapp.com
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports ={
entry: './src/index.js',
output: {
path: path.join(__dirname, 'build', 'static'),
filename: 'bundle.js'
},
module: {
rules: [
{
use: {loader: 'babel-loader'},
test: /\.js$/,
exclude: /node_modules/
}
]
},
devServer: {
host: 'localhost',
port: '8080'
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
}),
]
}
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"transform-class-properties",
["transform-object-rest-spread", { "useBuiltIns": true }]
]
}

Babel compiles with Webpack but not with Jest

I'm trying to setup Jest to work with my ES6 project using Babel with env preset. The code compiles and works with Webpack but not with Jest. Issue seems to be with transpiling code from inside of node_modules.
package.json (yarn) :
{
"name": "generative-toolbox",
"version": "0.0.1",
"main": "toolbox.js",
"repository": "git#bitbucket.org:yojeek/generative-toolbox.git",
"author": "msamoylov <antiplaka#gmail.com>",
"license": "MIT",
"private": true,
"scripts": {
"build": "yarn webpack --config webpack.config.js",
"test": "jest --debug"
},
"devDependencies": {
"babel-jest": "^22.4.3",
"jest": "^22.4.3",
"regenerator-runtime": "^0.11.1",
"webpack-cli": "^2.1.2"
},
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-register": "^6.26.0",
"dat.gui": "^0.7.1",
"enumify": "^1.0.4",
"event-pubsub": "^4.3.0",
"webpack": "^4.6.0"
},
"babel": {
"presets": [
["env"],
"stage-2"
],
"env": {
"test": {
"presets": [
["env", {
"targets": {
"node": "9.4.0"
},
"debug": true
}],
"stage-2"
]
}
}
}
}
webpack.config.js :
var path = require("path");
module.exports = {
entry: "./toolbox.js",
mode: 'development',
output: {
path: path.resolve(__dirname, "dist"),
filename: "generative.toolbox.js",
publicPath: '/dist/',
library : "GenT"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'
}
}
]
}
}
Definitions from toolbox.js :
import EventPubSub from 'event-pubsub'
class GUI {
gui
config
values
constructor() {
// some valid code
}
}
class MIDI extends EventPubSub {
midi
constructor() {
super()
// some valid code down there
}
}
test.js :
import {GUI, MIDI} from './toolbox.js'
test('gui sanity', () => { // <--- pass
let gui = new GUI()
expect(gui).toBeTruthy()
});
test('midi sanity', () => { // <--- fail
let midi = new MIDI()
expect(midi).toBeTruthy()
});
Test fails with following result :
TypeError: Class constructor EventPubSub cannot be invoked without 'new'
99 | midi
100 |
> 101 | constructor() {
102 | super()
103 |
104 | // request MIDI access
at new MIDI (toolbox.js:101:17)
at Object.<anonymous> (test.js:15:14)
So, because I want to extend ES6 Class from within node_modules I had to explicitly exclude it in jest config :
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!event-pubsub).+\\.js$"
]
}
That way the module will be imported to my test as it is (not transpiled).

Resources