Vue.js environment variables without vue-cli - javascript

What is the best way to load environment variables for Vue.js app without using vue-cli? In vue-cli way you just update the .env files and those variables should be available in Vue.js app like this: https://cli.vuejs.org/guide/mode-and-env.html#example-staging-mode
I am using Symfony Webpack Encore and have no vue-cli installed, how could I pass my environment variables into entire Vue application?

just create a .env file and create you variable like this VUE_APP_XXXXX
you notice the VUE_APP make sure all variable has the VUE_APP prefix like.
VUE_APP_API_URL
for development .env.development.
for production .env.production

Currently this looks like a decent way to load the configs: https://github.com/symfony/webpack-encore/issues/567
First install the dotenv package and then use this on my webpack.config.js:
const dotenv = require('dotenv');
.configureDefinePlugin(options => {
const dotenvOptions = {};
const envConfigPath = `.env.${process.env.NODE_ENV}`;
if (fs.existsSync(envConfigPath)) dotenvOptions.path = envConfigPath;
const env = dotenv.config(dotenvOptions);
if (env.error) {
throw env.error;
}
options['process.env'].PMP_API_BASE_URI = JSON.stringify(env.parsed.PMP_API_BASE_URI);
})
If .env.dev.local is needed then provide NODE_ENV=dev.local while running npm run build command.

Related

How to specify which .env file is used in Cypress Component Tests

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
},
});

Cannot find node module in rails stimulus controller

I have a problem with importing an npm package that I have created into my rails application.
I'm unsure if the problem is in the way I have created the node package or with the rails app.
The package is very simple -> https://www.npmjs.com/package/test-release-stuff
Now when I'm trying to import it into rails (I install it vie yarn and then see it's in the node modules) and I try to import it into my stimulus controller it tells me that it can't find the module. The error literally says:
Error: Cannot find module 'test-release'stuff'
How I'm importing the module?
I'm doing import foo from 'test-release-stuff'
One thing to note is that when I tried that in a simple react todo app it was imported without any issues.
I have a feeling that it might be something with the webpacker config in my rails app (below is the config) or that it might be something with the node packaga packgage.json file, there might be something incorrect there.
const { webpackConfig, merge } = require('#rails/webpacker');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const plugins = [];
if (process.env.ANALYZE === 'true') {
plugins.push(new BundleAnalyzerPlugin());
}
const customConfig = {
resolve: {
extensions: ['.css'],
},
plugins: plugins,
};
module.exports = merge(webpackConfig, customConfig);
then in the production/development/test files I have something like this:
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const webpackConfig = require('./base');
module.exports = webpackConfig;
It's a rails 6 project.
Turns out it was neither rails app fault or the node package fault.
I'm running the project inside the container. Although I installed once the previous version of that node package, when updating it, the changes were not properly reflected inside the container - I assume at some point the actual yarn command was not firing or that there was some caching involved.
After properly bringing the containers down, running docker-compose build and docker-compose up the changes were reflected and I can use the node package.

How do I access the process.env object of the importing class in an imported npm package?

I have a react app that sets a bunch of process.env variables using dotenv. Every component when it's source is in the same source code repo and imported via '../component/component_name' can access the process.env variables simply by using process.env.variable_name. We decided to break the components out into separate NPM packages in order to update them independent of the main repo. Now when we import them from our local NPM they intsall to node_modules and run, but cannot access the process.env variables. process.env shows up as an object, but it has nothing in it. We are using webpack to build the package before we publish it.
Inside component, you can do:
import process from "process";
const env = process.env;
export default env;

How to set a dynamic env var in node.js

I want to add a dynamic env var in my node.js app, in other words i wanted the env value to be determined through a function. so i can't add it manually in my .env file.
I'am using webpack as a module bundler and i want to access that env var in my webpack.config file.
Assuming you're running the node server on a linux machine. You need to export all your environment variables manually or via a script like so: export PORT=3000;, then accesses them directly via the node process object like so:
const port = process.env.PORT || 5000;.
Or you could install a dependency like config (https://www.npmjs.com/package/config) and have it manage pulling your environment variables into the code for use.

Is it possible to use dotenv in a react project?

I am trying to set some environment variables (for making API calls to dev/prod endpoints, keys depending on dev/prod, etc.) and I'm wondering if using dotenv will work.
I've installed dotenv, and I am using webpack.
My webpack entry is main.js, so in this file I've put require('dotenv').config()
Then, in my webpack config, I've put this:
new webpack.EnvironmentPlugin([
'NODE_ENV',
'__DEV_BASE_URL__' //base url for dev api endpoints
])
However, it is still undefined. How can I do this correctly?
Sorry for picking up old question, but
react-scripts actually uses dotenv library under the hood.
With react-scripts#0.2.3 and higher, you can work with environment variables this way:
create .env file in the root of the project
set environment variables starting with REACT_APP_ there
access it by process.env.REACT_APP_... in components
.env
REACT_APP_BASE_URL=http://localhost:3000
App.js
const BASE_URL = process.env.REACT_APP_BASE_URL;
See docs for more details.
The short answer is no. A browser cannot access local or server environment variables so dotenv has nothing to look for. Instead, you specify ordinary variables in your React application, usually in a settings module.
Webpack can be made to take environment variables from the build machine and bake them into your settings files. However, it works be actually replacing strings at build-time, not run-time. So each build of your application will have the values hard-coded into it. These values would then be accessible through the process.env object.
var nodeEnv = process.env.NODE_ENV;
Additionally, you could use the DefinePlugin for webpack which lets you explicitly specify different values depending on your build target (dev, prod, etc.). Note that you have to JSON.stringify all values passed into it.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
This is fine for any sort of public details but should never be used for any sort of private keys, passwords or API secrets. This is because any values baked in are publicly accessible and could be used maliciously if they contain sensitive details. For those sorts of things, you need to write some server-side code and build a simple API which can authenticate with the 3rd party API using the secrets, then pass the relevant details along to your client-side application. Your server-side API acts as an intermediary, protecting your secrets while still getting the data you need.
Create .env file
API_URL=http://localhost:8000
Install dotenv npm package
$ npm install --save-dev dotenv
Config webpack to add env variables
const webpack = require('webpack');
const dotenv = require('dotenv');
module.exports = () => {
// call dotenv and it will return an Object with a parsed key
const env = dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
plugins: [
new webpack.DefinePlugin(envKeys)
]
};
Great job! Enjoy React and dotenv.
Actually, you can use dotenv in your React app with webpack. Moreover, there are several ways of doing it. However, keep in mind that it's still a build-time configuration.
A similar way to the answer above. You import dotenv in your webpack config and use DefinePlugin to pass the variables to your React app. More complete guide on how you can inject your .env files depending on current configuration could be found in this blog.
Using a dotenv-webpack plugin. I personally find it really convenient. Let's say you have environments: dev, staging and prod. You create .env file for each environment (.env.dev, .env.staging, etc). In your webpack configuration you need to pick a correct file for the environment:
const Dotenv = require('dotenv-webpack');
module.exports = (env, argv) => {
const envPath = env.ENVIRONMENT ? `.env.${env.ENVIRONMENT}` : '.env';
const config = {
...
plugins: [
new Dotenv({
path: envPath
})
]
};
return config;
};
When you build the app for a particular environment, just pass the environment name to webpack:
webpack --config webpack.config.js --env.ENVIRONMENT=dev
I Just created a config.json in the source folder:
{
"api_url" : "http://localhost:8080/"
}
then required it in the file I needed it
const config = require('./config.json');
and used config.api_url

Categories