ReactJs Production Code- Uncaught ReferenceError: process is not defined - javascript

So I have a bit of an issue with by ReactJs production code where it doesn't seem to recognize my environment variables. This is the error I get:
Uncaught ReferenceError: process is not defined
<anonymous> webpack://testProject/./src/agent.js?:9
js http://localhost:8080/src_Admin_MainPage_SessionTimeout_index_js-src_agent_js-node_modules_moment_locale_sync_recursive_.js:29
__webpack_require__ http://localhost:8080/main.js:2511
fn http://localhost:8080/main.js:2789
<anonymous> webpack://coralpanda/./src/Admin/MainPage/Login/index.js?:5
js http://localhost:8080/src_Admin_MainPage_index_js.js:28
__webpack_require__ http://localhost:8080/main.js:2511
fn http://localhost:8080/main.js:2789
<anonymous> webpack://coralpanda/./src/Admin/MainPage/index.js?:4
js http://localhost:8080/src_Admin_MainPage_index_js.js:128
__webpack_require__ http://localhost:8080/main.js:2511
fn http://localhost:8080/main.js:2789
I followed Webpack's documentation for passing in environment variables and added them to my package.json file's build settings, but it didn't work. Here's how it looks:
"scripts": {
"start": "react-scripts start",
"build": "webpack --mode=production --env REACT_APP_SERVER_URL=https://localhost:3481/project --env NODE_PATH=./src --node-env=production",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build:dev": "webpack --mode=development",
"build:prod": "webpack --mode=production --node-env=production",
"watch": "webpack --watch",
"serve": "webpack serve"
},
And here is my webpack.config.js just in case:
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const WorkboxWebpackPlugin = require("workbox-webpack-plugin");
const isProduction = process.env.NODE_ENV == "production";
const stylesHandler = isProduction
? MiniCssExtractPlugin.loader
: "style-loader";
const config = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "build"),
},
devServer: {
open: true,
host: "localhost",
},
plugins: [
new HtmlWebpackPlugin({
template: "index.html",
}),
// Add your plugins here
// Learn more about plugins from https://webpack.js.org/configuration/plugins/
],
module: {
rules: [
{
test: /\.(js|jsx)$/i,
loader: "babel-loader",
},
{
test: /\.s[ac]ss$/i,
use: [stylesHandler, "css-loader", "postcss-loader", "sass-loader"],
},
{
test: /\.css$/i,
use: [stylesHandler, "css-loader", "postcss-loader"],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: "asset",
},
// Add your rules for custom modules here
// Learn more about loaders from https://webpack.js.org/loaders/
],
},
resolve: {
alias: {
assets: path.resolve(__dirname, 'src/assets/'),
agent: path.resolve(__dirname, 'src/agent.js'),
"agent.js": path.resolve(__dirname, 'src/agent.js'),
Admin: path.resolve(__dirname, 'src/Admin'),
}
},
};
module.exports = () => {
if (isProduction) {
config.mode = "production";
config.plugins.push(new MiniCssExtractPlugin());
config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
} else {
config.mode = "development";
}
return config;
};

Fixed the issue. The answer was EnvironmentPlugin. So I had to add that for webpack to recognize my environment variables. I added the following lines to my webpack.config.js:
const { EnvironmentPlugin } = require('webpack')
const config={
plugins:[
new EnvironmentPlugin({
REACT_APP_SERVER_URL: "https://localhost:3481/project",
NODE_PATH: "src/"
})
]
}

Related

How to access .env variable based on the mode

Let's say I have 2 files which are .env.development and .env.production.
In my package.json, since the mode is development, it should access .env.development for the variables.
"scripts": {
"start": "webpack-dev-server --config ./webpack.config.js"
webpack.config.js
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const Dotenv = require("dotenv-webpack");
module.exports = {
mode: "development",
entry: path.resolve(__dirname, "./src/index.jsx"),
devtool: "source-map",
output: {
path: path.join(__dirname, "/dist"),
filename: "bundle.js",
},
devServer: {
port: 3000,
static: true,
historyApiFallback: true,
open: true,
},
resolve: {...},
module: {...},
plugins: [
new Dotenv(),
new HtmlWebpackPlugin({
template: "public/index.html",
filename: "index.html",
favicon: "public/favicon.ico",
}),
new webpack.ProvidePlugin({
Buffer: ["buffer", "Buffer"],
}),
new webpack.ProvidePlugin({
process: "process/browser",
}),
],
};
So that in the frontend, when I use process.env, it will access the variable in .env.development.
Is there any way to do it?
You can set the system environment variable NODE_ENV at the beginning of the npm script. Use this environment variable to control the built environment.
E.g.
package.json:
"scripts": {
"build:dev": "webpack",
"build": "NODE_ENV=production webpack",
"dev": "webpack serve"
}
webpack.config.js:
const path = require("path");
const Dotenv = require("dotenv-webpack");
const mode =
process.env.NODE_ENV === "production" ? "production" : "development";
console.log("mode: ", mode);
module.exports = {
mode,
entry: path.resolve(__dirname, "./src/index.jsx"),
devtool: "source-map",
output: {
path: path.join(__dirname, "./dist"),
clean: true,
},
devServer: {
port: 3000,
static: true,
historyApiFallback: true,
open: true,
},
plugins: [
new Dotenv({
path: path.resolve(__dirname, `./.env.${mode}`),
}),
],
};
.env.development:
PWD=123456
.env.production:
PWD=a)d4125z
For development build npm run build:dev, the output of ./dist/main.js:
/******/ (() => { // webpackBootstrap
var __webpack_exports__ = {};
/*!***********************!*\
!*** ./src/index.jsx ***!
\***********************/
console.log("PWD: ", "123456");
/******/ })()
;
//# sourceMappingURL=main.js.map
For production build npm run build, the output:
console.log("PWD: ","a)d4125z");
//# sourceMappingURL=main.js.map

Getting 'ReferenceError: document is not defined' only when I run webpack --watch?

Why would document stop being defined only when I run webpack --watch? When I run my build or dev script, compiling works great. It's only when I try and watch. New to WP.
My end goal here is to polyfill my client-side JS and auto-reload the browser window that LiveServer opens (VSCode plugin). Right now, I'm just trying to automatically compile my code after making changes which will trigger LiveServer to reload. Is there a better approach to this?
index.js
const errors = document.querySelector('.errors');
webpack.config.js
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const NodemonPlugin = require('nodemon-webpack-plugin');
const config = {
watch: true,
entry: {
rater_stater: "./src/index.js",
},
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
// Creates `style` nodes from JS strings
MiniCssExtractPlugin.loader,
// Translates CSS into CommonJS
"css-loader",
// Compiles Sass to CSS
"sass-loader",
"postcss-loader",
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "style.css",
chunkFilename: "style-[id].css",
}),
new NodemonPlugin({
env: {
NODE_ENV: 'development',
},
})
],
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
config.devtool = "source-map";
}
if (argv.mode === "production") {
config.module.rules.push({
test: /\.js?$/,
use: [
{
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"],
},
},
],
exclude: /node_modules/,
});
}
return config;
};
package.json
"scripts": {
"build": "webpack --mode=production",
"dev": "webpack --mode=development",
"watch": "webpack --watch"
},
error
ReferenceError: document is not defined
at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180375
at /Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180732
at Object.<anonymous> (/Users/brad/Documents/vscode/rater-stater/dist/index.js:1:180735)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
Edit:
I'm also getting this error when it does compile with webpack --mode=development. It's like my variables are all set to null? I'm so confused. Why would this happen? I've tried changing it from var to let to const and still get the same error.
Edit 2:
Ran a couple more tests. It's like everything related to document is broken.. but I can console.log document. I just can't use querySelector, etc.
All of these issues stopped when I wrapped my code with
document.addEventListener("DOMContentLoaded", function() {
...code
}
🤦

I need help adding environment variables to my TypeScript toolchain

I am requesting help setting up the compilation and dev environment for a typescript library. The library should work when consumed by a web app framework and when consumed by a script tag. I am currently using Webpack as a dev server so I can debug and TSC to build (cjs + esm). The issue that prompted this post was having to constantly switch my API strings between http://localhost:8080 to https://production.com. What tools or changes do I need in order to build dev and prod variables into my compilation?
Here is what I'm doing so far:
package.json fragment
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"files": [
"lib/**/*",
"README.md"
],
"scripts": {
"build:esm": "tsc -p tsconfig.json --outDir lib/esm --module ES2020 --sourceMap false",
"build:cjs": "tsc -p tsconfig.json --outdir lib/cjs --module commonjs --sourceMap false",
"clean:build": "rimraf lib",
"clean:serve": "rimraf dist",
"build": "rimraf lib && npm run build:esm && npm run build:cjs",
"serve": "rimraf dist && webpack-dev-server"
}
webpack.config.js
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const SRC = path.resolve(__dirname, 'src')
const ENTRTY = path.resolve(__dirname, 'src', 'debug.ts')
const DIST = path.resolve(__dirname, 'dist')
module.exports = {
mode: 'development',
context: SRC,
entry: ENTRTY,
output: {
path: DIST,
filename: 'index.js',
},
devtool: 'source-map',
devServer: {
contentBase: DIST,
writeToDisk: true,
host: '0.0.0.0',
port: 8080,
https: true,
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin()
],
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{
test: /\.tsx?$/,
loader: 'ts-loader',
include: [SRC]
}
]
}
}
My toolchain does not currently allow me to do do this:
import Axios from 'axios'
import SocketIO from 'socket.io-client'
export const axios = Axios.create({
baseURL: process.env.SERVER_HTTP_URL, //<-- can't do env-vars with tsc build
withCredentials: true
})
typescript cant not do that, but gulp can do it
const replace = require('gulp-replace');
const { src, dest } = require('gulp');
exports.default = function() {
return src(['*.js'], {base: './'})
.pipe(replace('__XXXX__', 'some variables'))
.pipe(dest('./'));
}

how to set u a react/node project with babel and webpack?

i'm tryng to setup a new react project with babel and webpack but it's not working. this is my webpack.dev.config.js file :
var webpack = require('webpack');
var path = require('path');
var parentDir = path.join(__dirname, '../');
module.exports = {
entry: [
path.join(parentDir, '/react_components/index.js')
],
module: {
loaders: [{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
},
output: {
path: parentDir + '/html',
filename: 'main.js'
},
devServer: {
contentBase: parentDir,
historyApiFallback: true
}
}
and this is a screen shot from my project :
i get the message that webpack is compiled successfully but the main.js file remain empty
PS : i'm using this tutorial
https://medium.com/netscape/setting-up-a-react-project-from-scratch-d62f38ab6d97
Try running node node_modules\webpack\bin\webpack.js in project directory and it should build a phyisical main.js file.
The webpack-dev-server doesn't write to disk. It serves the result
from memory.
Source: https://github.com/webpack/webpack-dev-server/issues/24
Open package.json file. Inside scripts add "build": "webpack"
Your scripts object should essentially look something like this :
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server --hot",
"build":"webpack"
}
then run npm run build on your terminal.

Webpack.config.js configuration

Hello i'm trying to install this repo https://github.com/aepsilon and i ran npm i --no-bin-links, npm i webpack -g and other package but i cannot find how to configure my webpack.config.js because i got this error everytime i run npm start
webpack-dev-server --progress --colors --display-error-details --host=0.0.0.0
how can i configure my webpack.config.js https://github.com/webpack/webpack-dev-server/issues/183
here is my webpack.config.js and package.json
'use strict';
/* eslint-env node, es6 */
const path = require('path');
const webpack = require('webpack');
/////////////
// Utility //
/////////////
/**
* Recursively merges two webpack configs.
* Concatenates arrays, and throws an error for other conflicting values.
*/
function merge(x, y) {
if (x == null) { return y; }
if (y == null) { return x; }
if (x instanceof Array && y instanceof Array) {
return x.concat(y);
} else if (Object.getPrototypeOf(x) === Object.prototype &&
Object.getPrototypeOf(y) === Object.prototype) {
// for safety, only plain objects are merged
let result = {};
(new Set(Object.keys(x).concat(Object.keys(y)))).forEach(function (key) {
result[key] = merge(x[key], y[key]);
});
return result;
} else {
throw new Error(`cannot merge conflicting values:\n\t${x}\n\t${y}`);
}
}
/////////////////
// Base Config //
/////////////////
const srcRoot = './src/';
const commonConfig = {
entry: {
TMViz: [srcRoot + 'TMViz.js'],
main: srcRoot + 'main.js'
},
output: {
library: '[name]',
libraryTarget: 'var', // allow console interaction
path: path.join(__dirname, 'build'),
publicPath: '/build/',
filename: '[name].bundle.js'
},
externals: {
'ace-builds/src-min-noconflict': 'ace',
'bluebird': 'Promise',
'clipboard': 'Clipboard',
'd3': 'd3',
'jquery': 'jQuery',
'js-yaml': 'jsyaml',
'lodash': 'lodash',
'lodash/fp': '_'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
// Note on ordering:
// Each "commons chunk" takes modules shared with any previous chunks,
// including other commons. Later commons therefore contain the fewest dependencies.
// For clarity, reverse this to be consistent with browser include order.
// names: ['util', 'TuringMachine', 'TapeViz', 'StateViz'].reverse()
names: ['TMViz'].reverse()
})
],
module: {
loaders: [
// copy files verbatim
{ test: /\.css$/,
loader: 'file',
query: {
name: '[path][name].[ext]',
context: srcRoot
}
}
]
}
};
//////////////////////
// Dev/Prod Configs //
//////////////////////
const devConfig = {
output: {pathinfo: true}
};
const prodConfig = {
devtool: 'source-map', // for the curious
plugins: [
new webpack.optimize.OccurrenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({compress: {warnings: false}})
]
};
const isProduction = (process.env.NODE_ENV === 'production');
module.exports = merge(commonConfig, isProduction ? prodConfig : devConfig);
my package.json
{
"name": "turing-machine-viz",
"version": "1.0.0",
"description": "Turing machine visualization and simulator",
"homepage": "http://turingmachine.io",
"license": "BSD-3-Clause",
"author": "Andy Li <andy.srs.li#gmail.com>",
"repository": "aepsilon/turing-machine-viz",
"scripts": {
"clean": "trash build/ || rm -r build/",
"depgraph": "mkdir -p build/ && (cd src/ && madge . --dot) > build/depgraph.gv",
"depgraph-noext": "mkdir -p build/ && (cd src/ && madge . --dot -x \"`node -e \"console.log(Object.keys(require('../webpack.config').externals).map(s => '^'+s+'$').join('|'))\"`\") > build/depgraph-noext.gv",
"lint": "eslint --cache webpack.config.js src/",
"prod": "export NODE_ENV=production; npm run lint && webpack --progress --colors --display-error-details",
"start": "webpack-dev-server --progress --colors --display-error-details --host=0.0.0.0",
"watch": "webpack --watch --progress --colors --display-error-details"
},
"dependencies": {
"webpack-dev-server": "^2.9.5"
},
"devDependencies": {
"eslint": "^3.0.0",
"file-loader": "^0.8.5",
"raw-loader": "^0.5.1",
"webpack": "^1.12.9"
}
}
https://imgur.com/a/qdP18
Change the webpack version to 1.15.0 and webpack-dev-server to 1.16.5.
In the webpack.config.js line 77 change loader: 'file', to loader: 'file-loader',
Run npm install
Then enjoy your Turing Machine.
Thanks

Categories