JSDOM triggers webpack polyfill issues - javascript

I have a MERN project. As part of my attempt to deploy the frontend side to a server, I am trying to make it work in node environment.
The first issue:
when I attempt to run the following command in terminal:
node ./build/static/js/index.js
I get the following error:
Error: Automatic publicPath is not supported in this browser
at file://Users/123/JAN30/123reporter/front/dashboard/build/static/js/index.js:2:249085
at file://Users/123/JAN30/123reporter/front/dashboard/build/static/js/index.js:2:249226
at /Users/123/JAN30/123reporter/front/dashboard/build/static/js/index.js:152:80876
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
at async loadESM (node:internal/process/esm_loader:91:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
Node.js v18.12.1
which quite makes sense, as I'm attempting to run a .js code, which is expected to run in an environment of the browser, and I'm attempting to force it to run in a node environment.
So, to solve that, I was attempting to use jsdom in the following way:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './styles/index.css';
import App from './components/App';
import reportWebVitals from './reportWebVitals';
import { JSDOM } from "jsdom";
const dom = new JSDOM('<!doctype html><html><body><div id="root"></div></body></html>');
(global as any).window = dom.window;
global.document = dom.window.document;
const root: ReactDOM.Root = ReactDOM.createRoot(
window.document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
which lead me to ...
The second issue:
attempting to use JSDOM as written above triggered the following new issue
Module not found: Error: Can't resolve 'fs' in '/Users/123/JAN30/123reporter/front/dashboard/node_modules/jsdom/lib'
Alright. It make sense, as I am emulating a DOM environment in Nodejs environment, but it doesn't have the module found which Nodejs expects to have.
To solve that, I have added to my webpack.config file's module.export the following field:
node: {
fs: "empty",
},
now I try to rebuild, which leads me to.. surprise surprise..
The third issue:
Module not found: Error: Can't resolve 'path' in '/Users/123/JAN30/123reporter/front/dashboard/node_modules/jsdom/lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "path": require.resolve("path-browserify") }'
- install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "path": false }
I have tried solving that by adding in the webpack.config the following:
resolve: {
extensions: [".tsx", ".ts", ".js"],
fallback: {
path: require.resolve("path-browserify"),
},
},
yet, nothing's being changed. tried also modifying to
path: false;
same result.
Any ideas?
EDIT:
adding webpack config
const path = require("path");
const webpack = require("webpack");
const dotenv = require("dotenv");
dotenv.config();
module.exports = {
entry: {
index: "./src/index.tsx",
},
mode: "production",
node: {
fs: "empty",
},
module: {
rules: [
{
test: /\.tsx?$/,
use: [
{
loader: "ts-loader",
options: {
compilerOptions: { noEmit: false },
},
},
],
exclude: /node_modules/,
},
{
test: /\.css$/,
use: [
{
loader: "css-loader",
},
],
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
fallback: {
path: require.resolve("path-browserify"),
},
},
plugins: [
new webpack.DefinePlugin({
"process.env": JSON.stringify(dotenv.config().parsed),
}),
],
output: {
filename: "[name].js",
path: path.resolve(__dirname, "build/static/js"),
},
};
Regards :_)

Let's modify publicPath in (webpack.config.js) since it appears to be an empty string.
output: {
path: path.resolve(__dirname, 'path/to/output'),
filename: 'fileName.[ext]'
}

Related

Webpack Hot module replacement, react 18 ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before

I updated React to v18 and my Webpack dev server gives me a console error whenever the hot module replacement fires and injects the new javascript code:
Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root. render() on the existing root instead if you want to update it.
index.js file
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App />);
if (module.hot) module.hot.accept(function (err) {
console.log('An error occurred while accepting new version');
});
webpack.config.js
const path = require('path');
const HtmlWEbpackPlugin = require('html-webpack-plugin');
module.exports = (env) => {
let cfg = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.[contenthash:6].js',
publicPath: '/',
clean: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
]
},
plugins: [new HtmlWEbpackPlugin({ template: './src/index.html' })
],
devServer: {
static: {
directory: path.join(__dirname, 'public'),
},
compress: true,
port: 3000,
hot: true,
open: true,
},
performance: {
hints: false
}
}
return cfg;
};
React 18 has native support for hot reloading, this is called Fast Refresh. An excerpt from the react-refresh readme:
Fast Refresh is a feature that lets you edit React components in a running application without losing their state. It is similar to an old feature known as "hot reloading", but Fast Refresh is more reliable and officially supported by React.
To use this with Webpack 5, you will need a plugin called react-refresh-webpack-plugin. To get it to work I would recommend taking a look at the examples included in the git repository, especially the webpack-dev-server example.
NOTE: As of writing this answer, the react-refresh-webpack-plugin is in an experimental state but create-react-app is already using it, so it is probably stable enough to use.
The following is taken straight from react-refresh-webpack-plugin's webpack-dev-server example:
src/index.js
import { createRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);
webpack.config.js
const path = require('path');
const ReactRefreshPlugin = require('#pmmmwh/react-refresh-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isDevelopment = process.env.NODE_ENV !== 'production';
module.exports = {
mode: isDevelopment ? 'development' : 'production',
devServer: {
client: { overlay: false },
},
entry: {
main: './src/index.js',
},
module: {
rules: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
use: 'babel-loader',
},
],
},
plugins: [
isDevelopment && new ReactRefreshPlugin(),
new HtmlWebpackPlugin({
filename: './index.html',
template: './public/index.html',
}),
].filter(Boolean),
resolve: {
extensions: ['.js', '.jsx'],
},
};
babel.config.js
module.exports = (api) => {
// This caches the Babel config
api.cache.using(() => process.env.NODE_ENV);
return {
presets: [
'#babel/preset-env',
// Enable development transform of React with new automatic runtime
['#babel/preset-react', { development: !api.env('production'), runtime: 'automatic' }],
],
// Applies the react-refresh Babel plugin on non-production modes only
...(!api.env('production') && { plugins: ['react-refresh/babel'] }),
};
};
You can remove the following from your Webpack entry point:
src/index.js
// ...
if (module.hot) {
module.hot.accept()
}
This has the small drawback that whenever you modify your entry point (src/index.js) a full reload is necessary. Webpack is very in your face about needing to do a full reload, showing you the following log messages.
This really annoyed me. When looking at how create-react-app solved this, I found that they disabled client side logging for the webpack-dev-server, or at least set the log level to warn or error. You can set the log level by setting the client.logging property in the devServer configuration:
webpack.config.js
// ...
devServer: {
client: {
overlay: false,
logging: 'warn' // Want to set this to 'warn' or 'error'
}
}
// ...
What the odd thing is about the "warning", is that it is not a warning at all, it is just an info message dressed up as a warning.
Hope this helps.

Yarn Workspaces and Invalid Hook call

Having a lot of trouble trying to set up a common UI library.
I've set up a yarn workspace which looks like this:
/monorepo
/common-16.13
/react-app-16.8.
/another-app-16.13
I then import common-16.13 into react-app-16.8 and use one of the components like this:
/react-app/home.js
import {SharedComponent} from "common"
However when I run the application I get this error:
react.development.js?80c6:1465 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
Inside common I have:
/src/components/SharedComponent.jsx:
import React from 'react';
import { Box } from 'material-ui/core';
export const ShareComponent = ()=> <Box>SharedComponent</Box>;
/src/components/index.js:
export { SharedComponen t} from 'SharedComponent';
/src/index.js:
export {SharedComponent } from './components';
package.json:
{
"name": "#libs/common",
"main": "dist/index.js",
"scripts" {
"build": "webpack"
}
}
/common/webpack.config.json:
const webpack = require('webpack');
module.exports = env => {
// Each key value generate a page specific bundle
entry: {
index: './src/index.js'
},
output: {
path: path.resolve(ROOT_PATH, 'dist'),
publicPath: '/',
filename: 'index.js',
library: '#libs/common',
libraryTarget: 'umd'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: 'happypack/loader?id=jsx',
exclude: /node_modules/
}
]
},
// Automatically resolve below extensions
// Enable users to leave off the extensions when importing
resolve: {
symlinks: false,
extensions: ['*', '.js', '.jsx', '.css', '.scss']
},
plugins: [
new HappyPack({
id: 'css',
threadPool: happyThreadPool,
loaders: [
'cache-loader',
'style-loader',
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: true
}
},
'css-loader',
'sass-loader'
]
}),
new HappyPack({
id: 'jsx',
threadPool: happyThreadPool,
loaders: [
'cache-loader',
{
loader: 'babel-loader'
}
]
})
]
}
So I bundle common. Then in my react-app I yarn install #lib/common. Then I import SharedComponent into my react app:
/react-app/src/index.js:
import { SharedComponent } from '#libs/common';
/react-app/webpack.config.js:
{
// Each key value generate a page specific bundle
entry: {
index: './src/index.jsx',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader'
},
]
},
// Automatically resolve below extensions
// Enable users to leave off the extensions when importing
resolve: {
extensions: ['*', '.js', '.jsx', '.css', 'scss'],
alias: {
react: path.resolve('./node_modules/react'),
}
},
output: {
path: path.resolve(ROOT_PATH, 'dist'),
publicPath: '/',
filename: '[name].bundle.js',
chunkFilename: '[id].bundle.js'
},
};
It bundles fine but when I run the application I run into the error above. I can't tell if it's related to how i'm exporting my common components, but it it seems right. I read I should have a react alias in my app, which I do. I'm using yarn workspaces and not sure if that's related somehow.
Run the following command:
yarn why react
If the result shows that you have multiple versions of react:
Remove all local installations
Install a single version of React in the root workspace instead
this is probably a bug coming from yarn
issue:
https://github.com/yarnpkg/yarn/issues/8540
I did a workaround by:
exporting my common package into a new private github repo
create access token
https://docs.github.com/en/free-pro-team#latest/github/authenticating-to-github/creating-a-personal-access-token
in my package.json dependencies I added:
"common": "git+https://{accessToken}:x-oauth-basic#github.com/{user}/{repo}.git",
It happened to me when when migrating existing project to mono repo.
It was caused because I copied the lock files into the packages folders.
I've solved it by deleting any node_modules and any lock(yarn.lock and package-lock) from any package folder and then running yarn install on root directory.

React : You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file(Local Node module)

I have babel loader in the library. Still after I add the library to the react application while yarn serve, I get the above error.
This is the webpack.dev.config.js (required in the webpack.config.js) in library-
//webpack.dev.config.js
const babelRCPath = require('#appfabric/infra-scripts').getConfigPath('babel', 'plugin');
const babelRCGenerator = require(babelRCPath);
const babelRC = babelRCGenerator([]);
module.exports = {
{
BaseModule: `${process.cwd()}/src/BaseModule`,
BaseObject: `${process.cwd()}/src/BaseObject`,
BaseWidget: `${process.cwd()}/src/widgets/BaseWidget`,
HOCWidget: `${process.cwd()}/src/widgets/HOCWidget`,
PortalWidget: `${process.cwd()}/src/widgets/PortalWidget`,
BaseActivator: `${process.cwd()}/src/application/BaseActivator`,
CorePlugin: `${process.cwd()}/src/application/CorePlugin`,
BaseAppDelegate: `${process.cwd()}/src/application/appdelegates/BaseAppDelegate`,
EmbeddedAppDelegate: `${process.cwd()}/src/default/appdelegates/embedded/EmbeddedAppDelegate`,
ActionType: `${process.cwd()}/src/application/appdelegates/actions/ActionType`,
types: `${process.cwd()}/src/application/appdelegates/actions/types`,
CommandActionType: `${process.cwd()}/src/application/appdelegates/actions/CommandActionType`,
CommandForResponseActionType: `${process.cwd()}/src/application/appdelegates/actions/CommandForResponseActionType`,
PluginRegistryService: `${process.cwd()}/src/default/PluginRegistryService`,
},
mode: 'development',
externals: [
'dcl',
'react',
'react-dom',
'prop-types',
'pubsub',
'semver',
'#appfabric/ui-profiler',
].map(
// Add this regex to each entry to ensure we don't miss any imports like 'web-shell-core/...`
(value) => new RegExp(`^(${value})((\\\\|/|!).+)?$`),
),
output: {
path: `${process.cwd()}/build/dist`,
filename: '[name].js',
library: 'web-shell-core',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: babelRC,
},
},
],
},
};
This is the webpack.config.js
const developmentConfig = require('./webpack.dev.config.js');
module.exports = merge(developmentConfig, {
mode: 'production',
output: {
filename: '[name].min.js',
chunkFilename: '[name].min.js',
},
});
First I add a new file Secure.jsx(having the tags) in the library. I do npm install --save <path-to-library> on my application. After I do yarn install. Then I can see the new file Secure.jsx in the node modules in the application. When I try to run the application, I get the error.
Please let me know what am I missing and also which side(library / application) I have to add the code.
You can view my full config here
I think you also need to add this
resolve: {
modules: [
path.resolve('./node_modules')
]
},
Then import like this
import "jquery/dist/jquery.min.js";
import "bootstrap/dist/js/bootstrap.min.js";

Webpack JSX cannot resolve relative module through ES6 imports

I'm setting up webpack for a large already existing React App.
Seems to be working fine but some modules causes trouble unless I specifically add the extension to the import
//not working
import AppRouter from './router';
//working but meh
import AppRouter from './router.jsx';
It does not occur in all the relative imports but some for what I see look random.
The error, it occur multiple times for different files
ERROR in ./src/main/resources/js/cs/index.js
Module not found: Error: Can't resolve './router' in '<ommited_path>/src/main/resources/js/cs'
# ./src/main/resources/js/cs/index.js
The folder structure for that file
/src
--/main
--/resources
--/js/
--/cs
index.js
router.jsx
store.js
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const paths = require('./config/paths');
const config = {
entry: {
index: path.join(__dirname, paths.custServReactIndex),
},
output: {
path: path.join(__dirname, paths.outputScriptsFolder),
filename: '[name].js',
publicPath: paths.outputScriptsFolder,
},
mode: 'development',
module: {
rules: [
{
// Compile main index
test: /\.jsx?$/,
loader: 'babel-loader',
},
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
}),
],
};
module.exports = config;
.babelrc
{
"ignore": ["node_modules"],
"presets": ["env", "stage-0", "react"]
}
That being said, any idea on why some relative imports are failing and how can I solve so?
You need to add resolve extensions. Add the below config in Webpack and restart React app
resolve: {
modules: [
path.resolve("./src"),
path.resolve("./node_modules")
],
extensions: [".js", ".jsx"]
}

Angular 4 universal app with #angular/cli with third party (library/component) compilation

I am trying to implement server side rendering using angular universal. With followed this post angular-4-universal-app-with-angular-cli and this cli-universal-demo project, I encountered a problem as below.
When node starts dist/server.js it shows an error:
(function (exports, require, module, __filename, __dirname)
{ export * from ‘./scn-filter-builder’
scn-filter-builder is my module. It's written in angular2/typescript and node.js doesn't understand it.
The question is that can I set to universal so it will compile packages from node_module to es5 by itself? Or I need to compile my component into es5?
So I ended up tackling something similar to this by compiling it with Webpack. I just added a webpack.config.js with the following:
const path = require('path');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: {
server: './src/server.ts'
},
resolve: {
extensions: ['.ts', '.js']
},
target: 'node',
externals: [nodeExternals({
whitelist: [
/^ngx-bootstrap/
]
})],
node: {
__dirname: true
},
output: {
path: path.join(__dirname, 'server'),
filename: '[name].js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{ test: /\.ts$/, loader: 'ts-loader' }
]
}
}
Add the library that needs to be compiled in the nodeExternals -> whitelist area. In my case it was ngx-bootstrap. Then just run webpack to compile your file.

Categories