Here's my webpack.config.js
"use strict";
module.exports = {
entry: ['./main.js'],
output: { path: __dirname, filename: 'bundle.js' },
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
},
{test: /\.json$/, loader: "json"},
]
},
externals: {
React: 'react',
},
target: "node",
};
And Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
import Chart from 'chartjs';
import jQuery from 'jquery';
import vis from 'vis';
import babel from 'babel-core';
The Bundle.js is inserted in my Index.html. The browser then gives the error:
Uncaught ReferenceError: process is not defined
at Object.measureMethods (bundle.js:1297)
at Object.<anonymous> (bundle.js:530)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:288)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:158)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:110)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:90)
What should I change in the webpack.config.js to make this error go away?
For Webpack 5, you can reference process/browser from the appropriate plugins part of webpack.config.js:
// webpack needs to be explicitly required
const webpack = require('webpack')
// import webpack from 'webpack' // (if you're using ESM)
module.exports = {
/* ... rest of the config here ... */
plugins: [
// fix "process is not defined" error:
new webpack.ProvidePlugin({
process: 'process/browser',
}),
]
}
Then run
npm install process
before building.
For namespaced environment variables (more secure) check lines 10 - 28 on this StackBlitz page.
With dotenv package:
Install dotenv:
yarn add -D dotenv or npm i -D dotenv
Add .env file in your project root with the required variables:
NODE_ENV=development
apiKey=w23io222929kdjfk
domain=example.domain.org
Define these variables with webpack.DefinePlugin:
// webpack.config.js
const webpack = require('webpack')
const dotenv = require('dotenv')
// this will update the process.env with environment variables in .env file
dotenv.config();
module.exports = {
//...
plugins: [
// ...
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env)
})
// ...
]
//...
}
Access environment variables in your source code:
// src/index.js
alert(process.env.NODE_ENV)
alert(process.env.apiKey)
StackBlitz example: https://stackblitz.com/edit/node-kdfi4z?file=index.js
You need to add a plugin to define your env (in webpack config):
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
This is how i resolved the
ReferenceError: process is not defined
error with Webpack 5
npm i --save-dev process
Delete the "node_modules" folder
Add const webpack = require('webpack'); at the top of your config file
In your webpack config file, plugin section, add below:
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
Also in the webpack add the alias like below:
resolve: {
alias: {
process: "process/browser"
},
Now do npm i
...and when you build your application the error will disappear.
you can read about webpck migration [here]
Webpack 5 removes the ability to access environment variables using the notation process.env.MY_ENV_VAR. I had this same problem because I was getting a Uncaught ReferenceError: process is not defined error in my browser console. From the documentation of porting from v4 to v5 of Webpack, they mention the following:
1. Before upgrading to v5, verify that you can easily do it
Try to set the following options in your webpack 4 configuration and
check if build still works correctly.
module.exports = {
// ...
node: {
Buffer: false,
process: false
}
};
webpack 5 removes these options from the configuration schema and will always use false.
You have to remove these options again when upgrading your
configuration for webpack 5.
2. Handling env vars because process was removed
Regarding Runtime Errors:
process is not defined.
webpack 5 does no longer include a polyfill for this Node.js variable. Avoid using it in the frontend code.
Want to support frontend and browser usage? Use the exports or imports package.json field to use different code depending on the
environment.
Also use the browser field to support older bundlers,.
Alternative: Wrap code blocks with the typeof process checks. Note that this will have a negative impact on the bundle size.
Want to use environment variables with process.env.VARIABLE? You need to use the DefinePlugin or EnvironmentPlugin to define these
variables in the configuration.
Consider using VARIABLE instead and make sure to check typeof VARIABLE !== 'undefined' too. process.env is Node.js specific
and should be avoided in frontend code.
Therefore, given the above information, it is possible to use environment variables using one of the two plugins below.
const webpack = require("webpack");
module.exports = {
...
plugins: [
new webpack.DefinePlugin({
"process.env.MY_ENV_VAR": JSON.stringify(process.env.MY_ENV_VAR)
}),
new webpack.EnvironmentPlugin(['MY_ENV_VAR']); // <--This is shorthand, does the same thing as the DefinePlugin
],
};
Then in your production code it's still feasable to refer to the environment variable in the same way, example:
console.log(process.env.MY_ENV_VAR);
However, as they said in the documentation included above, using process.env is NOT the recommended way since that is Node.js specific.
Webpack 5, the easiest solution for me...
npm install dotenv-webpack --save-dev
// webpack.config.js
const Dotenv = require('dotenv-webpack');
module.exports = {
...
plugins: [
new Dotenv()
]
...
};
To avoid error like denoted in the question I had have provide in webpack.config.js the next configuration (note defining variable level: process.env):
new webpack.DefinePlugin({
"process.env": JSON.stringify(process.env)
})
Now it works fine. I'm using webpack 5.30.0, Vue 2.6.12 and vuelidate 0.7.6.
Error I had before in browser console:
Uncaught ReferenceError: process is not defined
at Object.../node_modules/vuelidate/lib/withParams.js
It is not good thing, that browser client library "vuelidate" requires Node.js specific env variables. Confused build and runtime areas in library.
Works for me to allow reading env variables inside React, using "webpack": "^5.1.3",
webpack.config.js
const webpackConfig = {
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser',
}),
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env)
})
],
};
:)
Having dotenv-webpack/dotenv in your webpack and still doesn't work on Angular? Most probably you're trying to access process.env when running the Angular app on the browser (without Angular Universal), e.g. by ng serve.
Run npm i -S process and then in polyfills.ts paste the code below
import * as process from "process";
window["process"] = process;
Alternatively, if that's not the case and you're looking for webpack to obtain environmental variables then (I don't know why no one suggested yet) dotenv-webpack is the simplest one.
const dotenv = require("dotenv-webpack");
const webpackConfig = {
plugins: [new dotenv()]
};
module.exports = webpackConfig; // Export all custom Webpack configs.
Of course you need to have them defined in .env file at the root of your project.
If it is useful for someone:
I tried almost every approach in this thread unsuccessfully.
When I went deeper into the problem I realized that what was causing this error on my application was the usage of assert lib:
import * as assert from 'assert';
...
assert(myVariable !== undefined, "Try to update undefined myVariable ");
BTW: I'm using Angular#~11.2.7
My problem was process is undefined error on internet explorer 11 using webpack 5.
This is how I solved my problem with process.env.MY_ENV_VAR thanks to #ArianPopalyar.
Ref. Answer
In addition to her solution, I added EnvironmentPlugin in webpack.config.js:
...
plugins: [
new webpack.ProvidePlugin({
process: 'process/browser'
}),
new webpack.EnvironmentPlugin({
PATH_MODERN: 'dist/modern/domready.min.js',
PATH_LEGACY: 'dist/legacy/domready.min.js',
DEBUG: false
}),
...
]
and using it in index.js
if (process.env.PATH_LEGACY) {
// ...
}
Easy way: prepend the variable "NODE_ENV" when you call webpack i.e. NODE_ENV=production webpack --watch
Related
So, I'm porting an old 2017 codebase from Webpack to Rollup for performance and code size reasons, also because of the old dependencies that the codebase used.
Unfortunately, The new Rollup version has a problem that I couldn't figure out a solution for. It doesn't seem to export some classes (In this case Engine and BackgroundLayer), but the Webpack unaltered version does. Is there a reason for this?
The Error in question:
Uncaught ReferenceError: Engine is not defined
Here's my rollup.config.js
import arraybuffer from '#wemap/rollup-plugin-arraybuffer';
import { babel } from "#rollup/plugin-babel";
import commonjs from "#rollup/plugin-commonjs";
import pkg from './package.json';
import resolve from "#rollup/plugin-node-resolve";
// import { terser } from "rollup-plugin-terser";
export default {
input: "src/index.js",
output: {
name: "index",
file: `dist/${pkg.name}.js`,
format: "umd",
},
external: ['ms'],
plugins: [
arraybuffer({ include: '**/*.dat' }), // so Rollup can import .dat files
resolve(), // so Rollup can find `ms`
commonjs(), // so Rollup can convert `ms` to an ES module
// terser(), // minifying
// babel configuration
babel({ exclude: 'node_modules/**', babelHelpers: "runtime", skipPreflightCheck: true }),
]
}
If anybody requires the full codebase, here are the two versions:
Webpack Code: https://github.com/kdex/earthbound-battle-backgrounds
Rollup Code: https://github.com/IamRifki/earthbound-battle-backgrounds-rollup
Figured it out, I had to call my bundle.js inside a module:
index.html
<script type="module">
import { BackgroundLayer, Engine } from "./bundle.js";
const engine = new Engine([new BackgroundLayer(153), new BackgroundLayer(298)]);
engine.animate();
</script>
I'm using node.js and webpack to create a bundle. From what I've read, node.js should contain fs module for managing files. However when I call require("fs") I get an Cannot find module "fs" error. What should I do?
I came across this problem myself when bundling with webpack and found the answer on this thread.
The way to solve it for me was to use the following config:
module.exports = {
entry: "./app",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [
{
test: /\.js$/,
exclude: 'node_modules',
loader: 'babel',
query: {presets: ['es2015']},
}
]
},
target: 'node'
};
By setting target to node webpack will make the necessary changes to bundle your node application
Edit: This answer targeted webpack 1.x which has now been superseded.
If you are running your webpack bundle in nodejs environment then target: 'node' is required in webpack.config.js file otherwise webpack takes default value as web for target check here.
You can resolve the issue in two ways
Add below configuration to your webpack.config.js
node: {
fs: "empty"
}
OR
Add below configuration to your package.json
"browser": {
"fs": false
}
Edit:
promising fix is
"browser": {
"fs": false
}
I had the same issue when bundling a NWjs application using webworkers (which in turn had node enabled).
The solution I found was to include each native module I used in externals with the prefix commonjs to the name of the module. For example:
...
target: "webworker", // or 'node' or 'node-webkit'
externals:{
fs: "commonjs fs",
path: "commonjs path"
}
...
I've done the same for targets "webworker" and "node-webkit" in different projects to solve the same issue.
webpack nwjs webworker nodejs node
Add below configuration to your webpack.config.js
resolve: {
fallback: {
fs: false
}
}
I needed to build a class that would use fetch if executed in a browser, or fs if executed in node. For other reasons, it was impractical to produce separate bundles, so I produced a single browser-targeted bundle.
The solution I used was to use eval('require("fs")') if the script was running in node.
const fs = eval('require("fs")')
Browser-safe (fs is null in the browser):
const fs = typeof window === 'object'
? null
: eval('require("fs")')
After trying everything I found on the internet (target, externals, node configs), the only solution that actually worked for me was replacing:
const filesystem = require("fs")
or
import fs from "fs"
by the special webpack version
const fs = __non_webpack_require__("fs")
This generates a require function that is not parsed by webpack.
In addition to the answer of PDG
I'm used to this short copy/paste candy.
Using path and fs :
var nodeModules = {};
fs.readdirSync(path.resolve(__dirname, 'node_modules'))
.filter(x => ['.bin'].indexOf(x) === -1)
.forEach(mod => { nodeModules[mod] = `commonjs ${mod}`; });
// Before your webpack configuration
module.exports = {
...
}
Then inside your configuration file, include the nodeModules variable in the externals
...
externals: nodeModules,
...
It would be more elegant to use pre-defined solution as:
Adding target: 'node' to webpack config file.
More info on: official documentation
For the solution we are building we had to force an older version of webpack:
npm install --save --force webpack#webpack-3
My web app uses Webpack 5.45.1 as a module bundler and the only library - ethereum web3.js 1.4.0.
// webpack configuration file
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");
const path = require('path');
module.exports = {
mode: 'development',
output: {
path: path.resolve(__dirname, 'dist/dev'),
filename: '[name].bundle.js',
},
entry: {
index: './src/index.js'
},
module: {
rules: [
{
test: /\.css$/,
use: ['css-loader'],
}
]
},
plugins: [
new NodePolyfillPlugin()
]
}
The entry point contains one single statement: import Web3 from 'web3';
Executing of the resulting bundle with a browser ends in the following error:
assertion_error.js:486 Uncaught TypeError: Cannot read property 'custom' of undefined
at eval (assertion_error.js:486)
at eval (assertion_error.js:500)
at Object../node_modules/assert/build/internal/assert/assertion_error.js (index.bundle.js:1063)
at __webpack_require__ (index.bundle.js:6721)
at eval (assert.js:38)
at Object../node_modules/assert/build/assert.js (index.bundle.js:1052)
at __webpack_require__ (index.bundle.js:6721)
at eval (index.js:3)
at Object../node_modules/console-browserify/index.js (index.bundle.js:1624)
at __webpack_require__ (index.bundle.js:6721)
I found it out, undefined is a value of this expression: require('util/').inspect.
Can anyone provide a hint on how it can be fixed?
This is because when you want to use web3 in the browser or in a client environment you have to manually include the prebuilt "node_modules/web3/dist/web3.min.js" in to your html with a script tag. That's the way it described in the documentation or you just get it from a cdn.
You should only do this:
import web3 from "web3";
if you want to run it in the nodejs runtime (Server side code or in the Command line).
If you insist on building this yourself then you have to clone the web3.js git repository and run npm run build, then get the /dist/web3.min.js file, and include it in a html script tag of your page, which is still pretty much the same thing and unnecessary.
Read the documentation carefully and see for your self.
web3.js github repo
As it turned out, in my case the problem was in NodePolyfillPlugin, which has a bug related to a circular dependency. I opened the issue on github.
I'm working on an Open Source D3/React component library and I'm trying to bundle the library using Rollup.js to offer code splitting, three shaking, etc.
The library is already published in GitHub and NPM and you can check a codesandbox using the library for a reference in case you want to try it.
Next I'm gonna try to highlight the different issues I'm experiencing with this bundle.
The library has already been tested using the code directly in a project and it works perfectly, so the problem is with the bundle and I assume that I'm doing something wrong with the Rollup.js configuration file in my project.
import { readdirSync } from 'fs';
import path from 'path';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import { terser } from 'rollup-plugin-terser';
const CODES = [
'THIS_IS_UNDEFINED',
'MISSING_GLOBAL_NAME',
'CIRCULAR_DEPENDENCY',
];
const getChunks = URI =>
readdirSync(path.resolve(URI))
.filter(x => x.includes('.js'))
.reduce((a, c) => ({ ...a, [c.replace('.js', '')]: `src/${c}` }), {});
const discardWarning = warning => {
if (CODES.includes(warning.code)) {
return;
}
console.error(warning);
};
const env = process.env.NODE_ENV;
const plugins = [
external(),
babel({
exclude: 'node_modules/**',
}),
resolve(),
replace({ 'process.env.NODE_ENV': JSON.stringify(env) }),
commonjs(),
env === 'production' && terser(),
];
export default [
{
onwarn: discardWarning,
input: 'src/index.js',
output: {
esModule: false,
file: 'umd/silky-charts.js',
format: 'umd',
name: 'silkyCharts',
},
plugins,
},
{
onwarn: discardWarning,
input: getChunks('src'),
output: [
{ dir: 'esm', format: 'esm', sourcemap: true },
{ dir: 'cjs', format: 'cjs', sourcemap: true },
],
plugins,
},
];
The Errors
When I try to use the library using the production bundle (which is the default) directly from the NPM package I got the following error coming from one of the chunks node_modules/silky-charts/esm/chunk-501b9e58.js:5833
TypeError: react__WEBPACK_IMPORTED_MODULE_0___default(...) is not a function
If I stead use the development bundle I get a different error:
Failed to compile
../silky-charts/esm/index.js
Module not found: Can't resolve 'react' in '/Users/davidg/Development/personal/silky-charts/esm'
This error force me to install React, ReactDOM, and styled-components as devDependencies in the project for the library have access to these projects code.
After installing the devDependencies the error I get is the next one:
Hooks can only be called inside the body of a function component.
I already filled an issue in the React project page and according to them this is not a React issue but maybe a Webpack's since is usual to find this error when you have to install React in both the project and the library and Webpack finds there is two instances of React, and I kind of agree since the error varies depending on bundle type or the way the importer project is run as you can see in the codesandbox.
I hope you can help me to spot the error in the Rollup configuration file and if you feel like doing a PR in the project event better 😀.
I'm trying to start a webapp with three.js, and i want to use webpack for bundling everything together, but i can't seem to figure out to require("webpack") on the webpak.config, i have to do this in order to use the webpack.providePlugin
Here is my webpack.config.js
var path = __dirname;
const webpack = require('webpack');
module.exports = {
entry: {
main: './main.js'
},
output: {
path: __dirname + '/dist/',
filename: '[name].bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader'
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
}
And here's the error that appears when i run webpack
Error on webpack run
The error only appears when i try to require webpack
I'm 99% sure the problem is that you're using an old version of Node.js.
Here's your error message:
/home/eloy/Sites/proyectomi/node_modules/webpack/lib/Compiler.js:10
const {
^
SyntaxError: Unexpected token {
If you're using Webpack 4.3 or 4.4 (the most current versions), then the line in question, line 10 of lib/Compiler.js, is the first line of this destructuring assignment:
const {
Tapable,
SyncHook,
SyncBailHook,
AsyncParallelHook,
AsyncSeriesHook
} = require("tapable");
A quick visit to node.green tells us that object destructuring wasn't supported in Node.js until version 6.4.0.
The webpack docs recommend using the current LTS release of Node.js:
Pre-requisites
Before we begin, make sure you have a fresh version of Node.js installed. The current Long Term Support (LTS) release is
an ideal starting point. You may run into a variety of issues with the
older versions as they may be missing functionality webpack and/or its
related packages require.
As of today (2018-03-30), that's Node.js 8.11.1.
1) var path = __dirname;
This line needs to be removed.
2) npm install webpack --save-dev
This will add webpack to dev dependencies.