Before you read this sorry for splitting my code into separate documents, it wat too long for Stackoverflow editor.
I get this error when i run my development environment:
Configuration file found but no entry configured.
Use --help to display the CLI options.
This is my webpack.config.js:
let config;
if (/development/.test(process.env.NODE_ENV.indexOf('development'))) {
config = require('./config/webpack.dev')({env: 'development'});
}
else if (/production|staging/.test(process.env.NODE_ENV)) {
config = require('./config/webpack.prod')({env: 'production'});
}
module.export = config;
This is my config/webpack.dev.js:
https://docs.google.com/document/d/1oudL50sL84FQDGB7vmuYcr2yVll44UlLr5DPPuZ2-kk/edit?usp=sharing
This is my webpack.common.js:
some code that i reuse for production and development environment
https://docs.google.com/document/d/1JMQPxMbLGsOGddohkZyhbvYE1CSXWImxJll3JVQ4rQA/edit?usp=sharing
This is my package.json:
https://docs.google.com/document/d/1uk5yXCjMbBCnhGqKzrQRAEUDewwPWd_UeW3Zld4oV7w/edit?usp=sharing
I print my screen to show the console.log i did for the config inside my webpack.config file when i run the npm run dev:
http://up416.siz.co.il/up3/eqho2ydz2j2t.png
This is my app structure:
http://up416.siz.co.il/up2/y2tni0ny11mt.png
I think Webpacks' error makes sense. It finds the configuration file, webpack.config.js, but there's no 'entry' property on the value that's exported.
Firstly, module.export should be module.exports. In your example, nothing will be exported, hence there being no entry property.
Once that's fixed, I think there's another issue; looks like the below condition is wrong:
/development/.test(process.env.NODE_ENV.indexOf('development'))
Should it be this instead?
/development/.test(process.env.NODE_ENV)
Since no conditions evaluate to true, config will be exported as undefined, which will probably give you the same error.
Related
i've been trying to figure out how to specify which .env file to use when running Cypress Component tests for a while now but can't seem to figure it out or find any information about it online.
I've noticed when you mount a Component in Cypress and run some Component Tests, the component will pick up process.env variables from the .env file by default. However, I would instead like Cypress to pick up process.env variables from my .env.test file. Does anyone know how to specify which .env file your component should get process.env variables from when running component tests?
I am currently just running the following command from my package.json file "test-e2e": "cypress open". This opens the Cypress test runner where I can select Component Testing and then select a spec file to run tests against. The component in question uses some process.env variables which I can see are being taken from the .env file which seems to be the default. I can't find any flags I can add to my npm command to instead tell Cypress to take them from the .env.test file instead.
Any help would be much appreciated!
You want to do something like this answer How can I get Vite env variables.
Note that the .env section of config is outside of component or e2e sections (common to both).
const { defineConfig } = require("cypress");
const dotenv = require('dotenv')
const env = dotenv.config('./.env.test').parsed
module.exports = defineConfig({
'component': {
// component config here
},
env: {
login_url: '/login',
...env, // merge here with spread operator
},
});
How can I conditionally import a module only in development mode (in my case the axios-mock-adapter package). Also the code should not even be present in the production bundle.
Example code I only want to be included during development:
export const mockUpClient = (api: AxiosInstance): void => {
// full api mocking, containing lots and lots of data
}
Now I am importing the module based on the following condition:
if (process.env.NODE_ENV === 'development') {
import("./apiMockAdapter").then((module) => {
module.mockUpClient(api)
})
}
The code is still included in the build, however it is not executed in production mode. How is it possible to completely exlude the code from the production bundle (of course without commenting out the code before every build)?
Update
The above example works fine. Before asking the question, I also imported the file from somewhere else, which led to this behaviour.
The accepted answer explains in detail how webpack will bundle the code & modules.
Basically:
Eject from create-react-app with npm run eject. You may be worried about the maintenance burden but it you look at the create-react-app repo you'll see there are very few meaningful changes in CRA and the upkeep with it is actually higher. If you are insistent on CRA then use craco.
Go to webpack.config.js (or craco.config.js if using craco)
Add an externals field if the app is running in production mode
Should look something like this. In this object add an externals part:
externals: isEnvProduction ? {
'myApiAdapter' : 'window' // or something else global
} : undefined,
This will map import('myApiAdapter') to window in production builds and not include it in the bundle.
That said, webpack should see the dynamic import as a point to break the bundle down into chunks, so it's unclear without seeing your actual code why it is included. Making that file external should bypass any such issues.
I am working on this react app and thinking of adding some environment variables inside, this is what I've done:
installed the latest version of react-scripts
added .env file on the root folder (the same location where node_modules folder is)
added REACT_APP_OTHER_OTHER_THING=asdfas just to test the variable
REACT_APP_OTHER_OTHER_THING=asdfas
open index.js and console.log(process.env.REACT_APP_OTHER_OTHER_THING) inside to see the output
import React from 'react';
import Reactdom from 'react-dom';
import App from './App';
console.log(process.env.REACT_APP_OTHER_OTHER_THING, 'DOTENV')
Reactdom.render(<App/>, document.getElementById("app"))
then I rebuilt the app and started the app to see the result
but then it gives out undefined as the output for process.env.REACT_APP_OTHER_OTHER_THING. I then tried to print process.env.NODE_ENV (which is working and prints "development" as output).
note: I have also tried to add temporary variable as the docs said in https://create-react-app.dev/docs/adding-custom-environment-variables >> rebuilt the server and run ($env:REACT_APP_OTHER_OTHER_THING= "abcdef") -and (npm start) << due to me running it on powershell which still gives undefined as output.
is there anything I can do on this?
thank you
Ensure it has correct directory tree
D:\your-react-project \ .env
Here it maybe your-react-project \ .env.development
It should be in the path of where default README.md placed
Alright, the problem I'm having seemed to be from the webpack I made in my React App,
I tried to follow the instruction from this article and it's working well!
after configuring my webpack, I rebuilt it, restart the server, and it works!
edit: for my solution, I added:
const dotenv = require('dotenv');
const env = dotenv.config().parsed;
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev; }, {});
at the top of webpack.common.js
and also added
plugins: [
new webpack.DefinePlugin(envKeys), //this line
]
in the module.exports
in the plugin. I hope this helps! :)
Can't comment, so i will post an answer, sorry.
Are you sure about ($REACT_APP_OTHER_OTHER_THING= "abcdef") -and (npm start), because docs says ($env:REACT_APP_NOT_SECRET_CODE = "abcdef") -and (npm start)
I just added new env var, and it gave me undefined, but after server restart it worked just fine. Can you try to restart server, but add env variable not in terminal, but inside .env file?
UPD1:
just so you know, NODE_ENV is set by npm start or npm run build commands, they set to development or production, respectively.
As docs says:
You cannot override NODE_ENV manually. This prevents developers from accidentally deploying a slow development build to production.
This worked for me with the same issue. I double-checked everything was connected correctly then killed my server in the terminal after started it back up & it worked fine.
Other causes of undefined environment variables on a much simpler level than the op's Webpack configuration question include:
Leaving out process.env.REACT_APP_SERVER_URL and just writing REACT_APP_SERVER_URL in your code
Forgetting to name the environment variable with REACT_APP as the first part of the string
I need to access command line parameters from npm script in my "constants.js" file.
I found I can access parameters in webpack.config.js file with process.env, but it is undefined in app source files.
I need to run the script from the console, for example:
npm webpack-dev-server --hot MY_PARAMETER=some_value
And then access MY_PARAMETER in my constants.js somehow, for example with:
process.env.MY_PARAMETER === "some_value" // true
Can somebody help? Thanks a lot.
If you have a .env file, your best bet will be to use dotenv-webpack (and optionally, string-replace-webpack-plugin or something similar). Reading the documentation, as a suggestion, you'll probably want to add a .env.local entry to your VCS ignore file (.gitignore, .hgignore, etc.) if you're concerned about safety, and call the new DotenvPlugin with an object that has path defined, i.e.,
const DotEnvPlugin = require('dotenv-webpack');
module.exports = {
/* other settings */
plugins: [
// other plugins,
new DotEnvPlugin({
path:'.env.local',
// safe: true, // load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
})
]
}
If you do not have a .env file, the above string-replace-webpack-plugin might be useful, and you just add those variables to your environment. (consult your OS/admin on how to do so)
Lastly, you can define them in a command-line call; they just typically need to go before any command issued, i.e. (in bash):
MY_PARAMETER=some_value node_modules/.bin/webpack-dev-server --hot
I am using node.js to create a web application. When I run the application (either by opening index.html on the browser or using the command "npm start" on the terminal) I get two errors:
Uncaught ReferenceError: process is not defined
Uncaught ReferenceError: require is not defined
I solved the "require is not defined" error by specifically including in my index.html head tag the link to this script, where the require function is defined.
However, I cannot find something similar for the process function.
My question is doublefold:
Why do built-in node.js modules need to be re-defined? Why are they not recognized as they are, that is "built-in modules"? Doesn't the term "built-in module" mean that a module need not be redefined externaly/second-handedly?
Is there a way to solve this problem? My script is very simple, I am just trying to use a basic function of node.js, so I cannot figure out what errors I might have done.
If anyone has come about this problem and has found a way around it or a reason this happens, you would be of great help.
Node.js code must be run by the node process, not the browser (the code must run in the server).
To run the code, you must run the command:
node server.js
And then you can access your server from a browser by typing "http://localhost:8080", for example. You must have a file server.js (or whatever) with the server code you want (in this case, creating a web server in port 8080).
You can follow this easy example, using express as http server module: http://expressjs.com/starter/hello-world.html
Webpack can inject environment variables into the "client side" .js code (very useful in case of SPA/PWA). You should define them as plugins in webpack.config.js
webpack.config.js
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.MY_ENV': JSON.stringify(process.env.MY_ENV),
... and so on ...
})
],
}
Now you can access it on client side:
app.js
// Something like that
if(process.env.NODE_ENV === 'debug'){
setDebugLevel(1)
}
If you are facing this problem and you are using webpack, you can get the desired process data injected into the client bundle by using DefinePlugin within your webpack.config.js.
In the example below, I show how to add several things to process.env object to make available within the browser:
all the environment variables inside .env using the library
dotenv
the value of NODE_ENV, which is either 'development' or 'production'
Working example
# .env
API_KEY=taco-tues-123
API_SECRET=secret_tacos
// webpack.config.js
const dotenv = require('dotenv').config({ path: __dirname + '/.env' })
const isDevelopment = process.env.NODE_ENV !== 'production'
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotenv.parsed),
'process.env.NODE_ENV': JSON.stringify(isDevelopment ? 'development' : 'production'),
}),
].filter(Boolean),
}
// Within client side bundle (React)
// src/App.jsx
console.log(process.env) // {API_KEY: "taco-tues-123", API_SECRET: "secret_tacos"}
console.log(process.env.NODE_ENV) // development
Notice that console.log(process.env) only has the values from the .env file, and that NODE_ENV is not a part of the process.env object.
In the example below, I show how I was trying to inject the process.env object which led me to this stack overflow. I also include a highlight from the webpack documentation on why the code below was not working.
Broken example
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
...dotenv.parsed,
'NODE_ENV': JSON.stringify(isDevelopment ? 'development' : 'production')
}
}),
].filter(Boolean),
}
// Within client side bundle (React)
// src/App.jsx
console.log(process.env) // Uncaught ReferenceError: taco is not defined
console.log(process.env.NODE_ENV) // development
From the webpack DefinePlugin docs:
Warning When defining values for process prefer
'process.env.NODE_ENV': JSON.stringify('production')
over
process: { env: { NODE_ENV: JSON.stringify('production') } }
Using the latter
will overwrite the process object which can break compatibility with
some modules that expect other values on the process object to be
defined.
!Warning!
Injecting dotenv.parsed into the client bundle as described will expose these secrets to the client. For development purposes, not a big deal, but in a deployed production environment, any passwords or private api keys will be visible to anyone that goes looking for them.
I had the same problem solved it by going into my .eslintrc.js file
to configure my globals variables, adding require and process to the globals variable and setting the corresponding value equal to "writable". Hope it works for you.
this link really helped
https://eslint.org/docs/user-guide/configuring#specifying-globals
I had same problem when I tried to do this node js app: https://www.youtube.com/watch?v=mr9Mtm_TRpw
The require in html was reached from a < script> and was undefined, like
<script> require('./renderer.js');</script>
I changed it to:
<script src="./renderer.js"></script>
The process in html script was also undefined. I included the webPreferences: nodeIntegration in the js file:
win = new BrowserWindow({
width: 800,
height:600,
icon: __dirname+'/img/sysinfo.png',
webPreferences: {
nodeIntegration: true
}
});
I hope it helped.
You can add the following to your package.json file
{
"name": "mypackage",//default
"version": "0.0.1", //default
"eslintConfig": {
"env": {
"browser": true,
"node": true
}
}}
More Explanation
I was just getting this error (Uncaught ReferenceError: process is not defined) in a local hot-reloading Quasar (Vue) app when calling a particular endpoint. The fix for me ended up being to just restart the hot-reloading server (I hadn't reloaded it since adding the process.env.MY_VARIABLE code).
If you are using the npm module dotenv-webpack with Webpack 3, it might be because you are using destructuring, like so:
const { ENV1, ENV2 } = process.env;
This is a known issue.
Ugly workaround is:
const { ENV1 } = process.env;
const { ENV2 } = process.env;
If you followed all answers here but still have same error then try this.
The error is caused by the react-error-overlay package which has dependencies that were updated to support webpack v5 and are not compatible with react-scripts v4.
So to solve the Uncaught ReferenceError: process is not defined in React, open your terminal in your project's root directory and update the version of your react-scripts package by running npm install react-scripts#latest and re-install your dependencies if necessary.
You can find more detailed answers in here
I had this issue, and for some reason no amount of fiddling around with the webpack.config.js using the other suggestions would resolve it. I suspect some packages I'm using are written incorrectly for the browser, or there might be something wrong with my environment.
I ended up "fixing" it by adding the following code to my HTML file above all other <script> file references. .
<script>
// Required by some npm packages
window.process = { browser: true, env: { ENVIRONMENT: 'BROWSER' } };
</script>