Angular: utils/util.js -> Uncaught ReferenceError: process is not defined - javascript

I feel like this should be resolved simply, but after several attempts, I'm just not coming to a resolution.
Here is the error I've received:
Uncaught ReferenceError: process is not defined
38509 # [PathToProject]\node_modules\util\util.js:109
This is getting triggered when I instantiate web3 into a clean/new site (there's two other 'test' components, one link one button)
I've searched and found numerous bits of information suggesting that
process is a server side 'node' var, and I can set this to be available client-side by adding to my webpack.config.js, which I have done.
I might be able to resolve by just declaring a global angular var in my app.component.ts, but it seems this dependency project .js file is not accessing it.
I've also tried just updating the dependency project directly, but even with a compile, it seems that my changes are not being distributed into the webpack build /dist/ result.
I think this probably has a blatantly simple solution, but I'm just overlooking it. I'm just spinning my tires here and could use a little help, but I'm the first in my circle to venture into web3 and don't have a close friend to bounce this off of. Can someone here provide some insight or an alternative resolve this issue?
Relevant bits of code:
webpack.config.js
var webpack = require('webpack');
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.(sass|less|css|ts)$/,
use: [
'ts-loader'
],
}
],
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': 'develop',
})
],
entry: './src/main.ts',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
resolve: {
extensions: [ '.js', '.ts', '.html' ],
modules: [
path.resolve(__dirname, 'node_modules/'),
path.resolve("", "src")
],
alias: {
Environments: path.resolve(__dirname, 'src/environments/'),
},
fallback: {
"fs": false,
"tls": false,
"net": false,
"path": false,
"zlib": false,
"http": require.resolve("stream-http"),
"https": require.resolve("https-browserify"),
"stream": false,
"crypto": require.resolve("crypto-browserify"),
"crypto-browserify": require.resolve('crypto-browserify'),
},
}
}
global-constants.ts
export class GlobalConstants {
public static process: any = {
env: {
NODE_ENV: 'development'
}
}
}
app.component.ts
import { Component } from '#angular/core';
import{ GlobalConstants } from './common/global-constants';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Cool Title';
process = GlobalConstants.process;
}
Relevant bit of utils/util.js (line 106-116)
var debugs = {};
var debugEnvRegex = /^$/;
if (process.env.NODE_DEBUG) {
var debugEnv = process.env.NODE_DEBUG;
debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
.replace(/\*/g, '.*')
.replace(/,/g, '$|^')
.toUpperCase();
debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
}

Add the following to polyfills.ts (usually inside src directory):
(window as any).global = window;
global.Buffer = global.Buffer || require('buffer').Buffer;
global.process = require('process');

Related

Rollup - not packaging entire repo (child component missing)

I have a component library written in vue that I am wrapping up with rollup
I am having an issue with mixins not being wrapped up into the final library. Intially i thought that the path was the issue as most of the mixins are local.
Originally:
import mixin from '../../mixins/color'
Repo folder structure
- dist //output
- src //All files related to the actual component within the library
- components
- comps
- alert //general components
- inputs //input components
- layout //layout components /row/col
- mixins
- utilities
- entry.js //rollup points to this
- ... //I used nuxt to develop the components to focus on SSR so there are more folders but are excluded in the rollup process
Apparently native rollup doesn't like indirect imports so I attempted to add rollup-plugin-includepaths. My understanding is that I would need to mention the paths required in the imports to work correctly.
Therefore, I added rollup-plugin-includepaths to rollup.config.js plugins and added the root path and the output director as the options
includePaths({
paths: ['src/components/', 'src/mixins/', 'src/utilities/'],
extensions: ['.js', '.vue']
}),
**this did not work **
I decided to remove all relative imports and create aliases for each required directory. This did not work either
What is happening is all mixins imported into the component and added as mixin: [mixins] //whatever they may be are not included in the compiled product?!?!?!
What am I missing????
// rollup.config.js
import fs from 'fs'
import path from 'path'
import vue from 'rollup-plugin-vue'
import alias from '#rollup/plugin-alias'
import commonjs from '#rollup/plugin-commonjs'
import replace from '#rollup/plugin-replace'
import babel from 'rollup-plugin-babel'
import { terser } from 'rollup-plugin-terser'
import minimist from 'minimist'
import postcss from 'rollup-plugin-postcss'
import includePaths from 'rollup-plugin-includepaths'
import del from 'rollup-plugin-delete'
// Get browserslist config and remove ie from es build targets
const esbrowserslist = fs
.readFileSync('./.browserslistrc')
.toString()
.split('\n')
.filter(entry => entry && entry.substring(0, 2) !== 'ie')
const argv = minimist(process.argv.slice(2))
const projectRoot = path.resolve(__dirname)
const baseConfig = {
input: 'src/entry.js',
plugins: {
preVue: [
alias({
resolve: ['.js', '.jsx', '.ts', '.tsx', '.vue'],
entries: [
{ find: '#', replacement: path.resolve(projectRoot, 'src') },
{
find: '#mixins',
replacement: path.resolve(projectRoot, 'src', 'mixins')
},
{
find: '#comps',
replacement: path.resolve(projectRoot, 'src', 'components', 'comps')
},
{
find: '#inputs',
replacement: path.resolve(
projectRoot,
'src',
'components',
'inputs'
)
},
{
find: '#utilities',
replacement: path.resolve(projectRoot, 'src', 'utilities')
}
]
}),
includePaths({
paths: ['src/components/', 'src/mixins/', 'src/utilities/'],
extensions: ['.js', '.vue']
}),
commonjs(),
postcss()
],
replace: {
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.ES_BUILD': JSON.stringify('false')
},
vue: {
css: false,
template: {
isProduction: true
}
},
babel: {
exclude: 'node_modules/**',
extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue']
}
}
}
// ESM/UMD/IIFE shared settings: externals
// Refer to https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency
const external = [
// list external dependencies, exactly the way it is written in the import statement.
// eg. 'jquery'
'vue'
]
// UMD/IIFE shared settings: output.globals
// Refer to https://rollupjs.org/guide/en#output-globals for details
const globals = {
// Provide global variable names to replace your external imports
// eg. jquery: '$'
vue: 'Vue'
}
// Customize configs for individual targets
const buildFormats = []
if (!argv.format || argv.format === 'es') {
const esConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.esm.js',
format: 'esm',
exports: 'named'
},
plugins: [
del({ targets: 'dist/*' }),
replace({
...baseConfig.plugins.replace,
'process.env.ES_BUILD': JSON.stringify('true')
}),
...baseConfig.plugins.preVue,
vue(baseConfig.plugins.vue),
babel({
...baseConfig.plugins.babel,
presets: [
[
'#babel/preset-env',
{
targets: esbrowserslist
}
]
]
})
]
}
buildFormats.push(esConfig)
}
if (!argv.format || argv.format === 'cjs') {
const umdConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.ssr.js',
format: 'cjs',
name: 'Components',
exports: 'named',
globals
},
plugins: [
replace(baseConfig.plugins.replace),
...baseConfig.plugins.preVue,
vue({
...baseConfig.plugins.vue,
template: {
...baseConfig.plugins.vue.template,
optimizeSSR: true
}
}),
babel(baseConfig.plugins.babel)
]
}
buildFormats.push(umdConfig)
}
if (!argv.format || argv.format === 'iife') {
const unpkgConfig = {
...baseConfig,
external,
output: {
compact: true,
file: 'dist/comps.min.js',
format: 'iife',
name: 'Components',
exports: 'named',
globals
},
plugins: [
replace(baseConfig.plugins.replace),
...baseConfig.plugins.preVue,
vue(baseConfig.plugins.vue),
babel(baseConfig.plugins.babel),
terser({
output: {
ecma: 5
}
})
]
}
buildFormats.push(unpkgConfig)
}
// Export config
export default buildFormats
Update
I moved the imported components out of the mixin and added them directly to the component that included them and got the same result. Therefore, i really have no clue what needs to happen.
TL;DR
None of the child components are being included in the rolled up dist '.js' files
Sometimes it is hard to include what is relevant and the question above is guilty.
The problem is within the larger component I had imported the children lazily
ex:
components:{
comp: ()=>import('comp') ///Does not work
}
changed to your standard
import comp from 'comp'
components:{
comp
}

Webpack: Trying to expose a bundled object to be usable by other scripts, object is still undefined

I'm trying to get just the basics down, transpiling a jsx file to js. However, my transpiled code needs to be called by non-transpiled code. output.library is supposed to help with that.
In the resulting bundle I see a definition for var react. But just after stepping through the entire bundle, it's clear react still isn't getting set.
my webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: "./public/js/ui/react/dialog.jsx",
output: {
path: path.resolve(__dirname, "public/js/ui/react/"),
filename: "bundle.js",
libraryTarget: "var",
library: "react"
},
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: [
path.resolve(__dirname, "node_modules/")
],
query: {
presets: ['es2015', "react"]
}
}
]
},
node: {
fs: "empty"
}
}
and the jsx I am trying to transpile:
'use strict';
react.Dialog = class extends React.Component {
render() {
return (
<div class="bubble-speech">Hello World</div>
)
}
}
elsewhere in my code, AND BEFORE THE BUNDLE, I have this, so that the react.Dialog assignment is not a null reference error:
var react = {};
If I take that one line away, the bundle.js will throw an error trying to assign react.Dialog. But if I leave it in, var react remains set to the empty object. That seems like a contradiction! What am I missing here?
I think react should be set as an externally defined global var, like this:
{
output: {
// export itself to a global var
libraryTarget: "var",
// name of the global var: "Foo"
library: "Foo"
},
externals: {
// require("react") is external and available
// on the global var React
"react": "React"
}
}

React.js and webpack - why won't it allow var, let, const?

I have a bit of an issue here that I can't get to the bottom of.
Here's a snippet from my Graph.js file:
class Graph extends React.Component {
#observable newTodoTitle = "";
s = 40
There error in webpack is as follows:
ERROR in ./src/components/Graph.js
Module build failed: SyntaxError: Unexpected token (13:6)
2018-01-11T14:56:05.221073500Z
11 |
12 |
> 13 | let s = 40
| ^
If I remove the "let", it compiles fine!
I'd prefer to keep the var, let, consts, etc. as I want to copy and paste a lot of JavaScript into this file without these errors.
Here's my .babelrc
{
"presets": [
"react",
"es2015",
"stage-1"
],
"plugins": ["transform-decorators-legacy"]
}
And here's my webpack.config.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [{
test: /\.jsx?$/,
use: ['babel-loader'],
include: path.join(__dirname, 'src')
}]
}
};
Any ideas?
You are trying to use the class-fields proposal (stage 3 currently) which you will need the Class properties transform plugin of babel to support this.
As you can see in the docs, your syntax is off.
There is no need for any variable declaration key word for class fields.
Example from the docs:
class Counter extends HTMLElement {
x = 0;
clicked() {
this.x++;
window.requestAnimationFrame(this.render.bind(this));
}
constructor() {
super();
this.onclick = this.clicked.bind(this);
}
connectedCallback() { this.render(); }
render() {
this.textContent = this.x.toString();
}
}

Webpack, React.js - require not defined error in browser console

I'm trying to build a web app with a React.js front-end, Express handling the back-end and Webpack bundling the whole thing. I'm trying to move away from my habitual way of doing things which is creating separate webpack.config files for the server and client. I'm also trying to add a minifier (Babili).
Here is my webpack.config file. Note how I used object.assign to create different objects for my client and server files and how I export them at the very end. I doubt this is where the problem lies.
const BabiliPlugin = require('babili-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const srcPath = path.resolve(__dirname + '/src');
const distPath = path.resolve(__dirname + '/dist');
// Common entries for all configs
var common = Object.assign({}, {
context: srcPath,
resolve: {
modules: ['node_modules', 'src'],
extensions: ['*']
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new BabiliPlugin()
],
externals: nodeExternals()
});
// Server.js config
// Output to dist/client/
var serverConfig = Object.assign({}, common, {
entry: './server/index.js',
output: {
path: distPath,
filename: 'server.min.js'
},
target: 'node',
node: {
__dirname: false,
__filename: false
}
});
// Client.js config
// Output to /dist/
var clientConfig = Object.assign({}, common, {
entry: "./client/index.js",
output: {
path: distPath,
filename: './client/client.min.js',
publicPath: '/'
},
target: 'web',
devtool: 'source-map'
});
// Export configurations array
module.exports = [serverConfig, clientConfig]
Here is my client.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route } from 'react-router-dom';
import Home from './routes/Home.js';
ReactDOM.render((
<div>
<p> why is this not working </p>
</div>
), document.getElementById('app'));
The error I get in the browser console is the following :
Uncaught ReferenceError: require is not defined
at Object.<anonymous> (client.min.js:1)
at b (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at b (client.min.js:1)
at client.min.js:1
at client.min.js:1
I don't understand why it wouldn't work. The server.js file works fine since I can see the index.html file is served to the browser. My usual webpack.config files are the exact same except for the Babili minifier, which when removed does not solve the issue. I'm hoping you guys can help me out with this. Thank you in advance!
Edit: I'd like to add the fact I did not have the nodeExternals() part in my previous client config. However, when I don't include it, I get the following error:
Uncaught Error: Cannot find module "object-assign"
at client.min.js:8
at client.min.js:8
at Object.<anonymous> (client.min.js:8)
at Object.<anonymous> (client.min.js:8)
at t (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at t (client.min.js:1)
at Object.<anonymous> (client.min.js:1)
at t (client.min.js:1)
externals: nodeExternals () tells Webpack to load all modules using require. This is useful for the server but throws this error in the browser (because require is only natively present on Node.js).
To fix it simply move the externals field to the server config :
// Common entries for all configs
var common = Object.assign({}, {
context: srcPath,
resolve: {
modules: ['node_modules', 'src'],
extensions: ['*']
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
plugins: [
new BabiliPlugin()
]
});
// Server.js config
// Output to dist/client/
var serverConfig = Object.assign({}, common, {
entry: './server/index.js',
output: {
path: distPath,
filename: 'server.min.js'
},
target: 'node',
node: {
__dirname: false,
__filename: false
},
externals: nodeExternals()
});

Dynamically loading an external webpack bundled ngModule as a route handler

We want to divide our large frontend projects into multiple separately deployed projects which are easier to work with. I am trying to include a bundled ngModule to handle a route from within another app. The apps must be ignorant of each other's configuration. The bundles will share some large dependencies(like Angular) via globals. We don't need to shake across the bundles and we may just have to accept some duplicate dependencies.
The root router complains that
Error: No NgModule metadata found for 'TestsetModule'.
which leads me to believe the child module is not being angular compiled on load, or is not registering its module for some reason. I think it may be necessary to manually compile the module, but I'm not sure how to use this https://angular.io/api/core/Compiler#compileModuleAndAllComponentsAsync
The root app loads the child via a route:
import { ModuleWithProviders } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
const load = require("little-loader");
const routes: Routes = [
{ path: ``, loadChildren: () => new Promise(function (resolve) {
load('http://localhost:3100/testset-module-bundle.js',(err: any) => {
console.log('global loaded bundle is: ', (<any>global).TestsetModule )
resolve((<any>global).TestsetModule)
}
)
})}
];
export const HostRouting: ModuleWithProviders = RouterModule.forRoot(routes);
I also tried using angular router's string resolution syntax rather than this weird global thing you see but I had similar issues.
Here is the module which is being loaded, very standard except for the global export:
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { HttpModule } from '#angular/http';
//import { MaterialModule } from '#angular/material';
import { FlexLayoutModule } from '#angular/flex-layout';
import { FormsModule } from '#angular/forms';
import { LoggerModule, Level } from '#churro/ngx-log';
import { FeatureLoggerConfig } from './features/logger/services/feature-logger-config';
import { TestsetComponent } from './features/testset/testset.component';
import { TestsetRouting } from './testset.routing';
#NgModule({
imports: [
CommonModule,
//MaterialModule,
FlexLayoutModule,
HttpModule,
FormsModule,
LoggerModule.forChild({
moduleName: 'Testset',
minLevel: Level.INFO
}),
TestsetRouting,
],
declarations: [TestsetComponent],
providers: [
/* TODO: Providers go here */
]
})
class TestsetModule { }
(<any>global).TestsetModule = TestsetModule
export {TestsetModule as default, TestsetModule};
Here is the webpack configuration of the root bundle. Note the global exports via the poorly named "ProvidePlugin".
const webpack = require('webpack');
const AotPlugin = require('#ngtools/webpack').AotPlugin;
const path = require('path');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const PolyfillsPlugin = require('webpack-polyfills-plugin');
const WebpackSystemRegister = require('webpack-system-register');
module.exports = (envOptions) => {
envOptions = envOptions || {};
const config = {
entry: {
'bundle': './root.ts'
},
output: {
libraryTarget: 'umd',
filename: '[name].js',//"bundle.[hash].js",
chunkFilename: '[name]-chunk.js',
path: __dirname
},
externals: {
},
resolve: {
extensions: ['.ts', '.js', '.html'],
},
module: {
rules: [
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.css$/, loader: 'raw-loader' },
]
},
devtool: '#source-map',
plugins: [
new webpack.ProvidePlugin({
'angular': '#angular/core',
'ngrouter': '#angular/router',
'ngxlog':'#churro/ngx-log'
})
]
};
config.module.rules.push(
{ test: /\.ts$/, loaders: [
'awesome-typescript-loader',
'angular-router-loader',
'angular2-template-loader',
'source-map-loader'
] }
);
}
return config;
};
And here is the webpack configuration of the child bundle. Note the "externals" which look for angular as a global.
module.exports = (envOptions) => {
envOptions = envOptions || {};
const config = {
entry: {
'testset-module-bundle': './src/index.ts'
},
output: {
//library: 'TestsetModule',
libraryTarget: 'umd',
filename: '[name].js',//"bundle.[hash].js",
chunkFilename: '[name]-chunk.js',
path: path.resolve(__dirname, "dist")
},
externals: {
//expect these to come from the app that imported us
// name to be required : name from global
'angular': '#angular/core',
'ngrouter': '#angular/router',
'ngxlog': '#churro/ngx-log'
},
resolve: {
extensions: ['.ts', '.js', '.html'],
},
module: {
rules: [
{ test: /\.html$/, loader: 'raw-loader' },
{ test: /\.css$/, loader: 'raw-loader' },
]
},
devtool: '#source-map',
plugins: [
]
};
config.module.rules.push(
{ test: /\.ts$/, loaders: [
'awesome-typescript-loader',
'angular-router-loader',
'angular2-template-loader',
'source-map-loader'
] }
);
}
return config;
};
And for good measure here is my tsconfig file which 'awesome-typescript-loader' reads.
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true,
"baseUrl": ".",
"rootDir": "src",
"outDir": "app",
"paths": {
"#capone/*": [
"*"
],
"#angular/*": [
"node_modules/#angular/*"
],
"rxjs/*": [
"node_modules/rxjs/*"
]
}
},
"exclude": ["node_modules", "src/node_modules", "compiled", "src/dev_wrapper_app"],
"angularCompilerOptions": {
"genDir": "./compiled",
"skipMetadataEmit": true
}
}
If you're still reading, awesome. I was able to get this working when both bundles are part of the same webpack config and the child module is just a chunk. Angular is designed to do that. But our use case is to have the children and parent be ignorant of each other until runtime.
As you have mentioned
The apps must be ignorant of each other's configuration.
I had a similar problem in Angular2. I solved it by creating a sub-application. A separate sub-main.browser.ts and index.html file. It had its own dependencies, sharing the same node modules. Both main modules bootstrapping different app-component. We were working on Angular without angular-cli.
In webpack config, I added
entry: {
'polyfills': './src/polyfills.browser.ts',
'main' . : './src/main.browser.aot.ts',
'sub-main' : '/src/sub-main.browser.ts'
},
and a more detailed HtmlWebpackPlugin. In the chunks, we load only modules that will be used in both the app. If we see polyfills is common.
new HtmlWebpackPlugin({
template: 'src/index.html',
title: METADATA.title,
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head',
chunks: ['polyfills','main']
}),
new HtmlWebpackPlugin({
template: 'src/index2.html',
title: 'Sub app',
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head',
filename: './sub-app.html',
chunks: ['polyfills','sub-main']
}),
The next task was to create separate endpoints for both sub apps for dev environment.
devServer: {
port: METADATA.port,
host: METADATA.host,
historyApiFallback: true,
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
proxy: {
"/sub-app": {
target: "http://localhost:3009",
bypass: function(req, res, proxyOptions) {
return "/index2.html";
}
}
}
},
Now when I build the project two different HTML files are generated. Each with their own javascript bundle dependencies and common assets. They can be deployed on a different server as well.
I was able to finish my POC with lots of trial and error. My suggestion will be to look a step above angular. See how webpack is deploying your current project. And If you can configure it to serve your purpose.

Categories

Resources