external .env for bundled vue-cli SPA - vue.js

I tried to use dotenv-webpack, but the .env also included in the bundle.
What I wanted to do is to make the .env readable after the build.
static/
index.html
.env
is this possible on spa's?

No, this is not possible with the standard Vue-CLI/Webpack unless you search inside the bundled gibberish of your code.
If your intention is to do something with the bundled data like changing values inside your .env then there is a way to hook your app with a env.js file, but this should not contain sensitive data.
Explanation of post- "env.js" hook:
you have to check for a global variable somewhere in you code.
i make a example of changing the axios baseURL after bundling the project.
place a js file like "env.js" in the first place of initialization in your web server.
// env.js
document.env = 'https://www.use-other-api.com'
so "document.env" is now declared before your app runs
then you have a hook in your project which is prepared for this "after bundled env changes"
like:
if (document.env === 'https://www.use-other-api.com') {
// change axios baseURL to "document.env"
} else {
// stay default baseURl
}
and that's it.
just be aware of not using any sensitive data in this scope because it is accessible anywhere in your app.
like i would not recommend you to put in some secrets depending in your backend stuff.

No, the .env file should be loaded on the server that runs your app. That's what it's name stands for. It consists of enviromental variables that you can use globally.
You can find more...
https://codeburst.io/process-env-what-it-is-and-why-when-how-to-use-it-effectively-505d0b2831e7

Related

Adding a houdini paintworklet in a nuxt3/vue app

I am trying to add a paintworklet to my application, but I am having a really hard time.
The worklet is a npm dependency, but worklets can't be inlined, they need to be registered like so:
CSS.paintWorklet.addModule('url/to/module.js');
I am having a hard time, because even though that currently works in my application, I am not sure if this is the right way to go about it, or if it will work in production. Currently, my url points to a file inside node_modules and I am not sure if nuxt will do anything with this.
I am currently doing this with a .client.js file inside the plugins folder. But they need an export default function(), but the worklet code does not have an export.
What I am currently trying to do, is tell nuxt somehow to grab certain files from node_modules and serve them as assets somehow, and then reference them some other way. But I cannot find any resources on this.
Any ideas would be appreciated.
If the file path is specified in a literal string, containing node_modules, the paint worklet might appear to work in development mode, but the worklet file will not be bundled in the build output:
CSS.paintWorklet.addModule('./node_modules/extra-scalloped-border/worklet.js')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
❌ file not bundled in build output
Solution: Import the file
Importing a file enables the bundler to track the file, and include it in the build output. Nuxt 3 uses Vite by default, and the Vite docs describe how to import the file to use with paint worklets:
Explicit URL Imports
Assets that are not included in the internal list or in assetsInclude, can be explicitly imported as an URL using the ?url suffix. This is useful, for example, to import Houdini Paint Worklets.
import workletURL from 'extra-scalloped-border/worklet.js?url'
CSS.paintWorklet.addModule(workletURL)
Since the CSS.paintWorklet API is only available in the browser, make sure to use this in the mounted() hook, which only occurs client-side:
import workletURL from 'extra-scalloped-border/worklet.js?url'
export default {
mounted() {
CSS.paintWorklet.addModule(workletURL)
}
}
demo

Where to install 3rd party scripts in Nuxt?

Im trying to upload static files(images and js) from "static" folder. And it works fine for index file and base route localhost:8000/, but if I go to the next route localhost:8000/reviews/master001 then static files disappears and I receive by route localhost:8000/reviews/js. And there is two things, first is how to remove prefix "reviews"?
I tried to use in nuxt.config.js
static: {
prefix: false
}
by documentation, but it does not work. Tried to use paths in nuxt.config like "../js", "#/static/js", "/js" - this one works for index file.
Also there are no any static files after I go through the router-link such it in nuxt documentation for path localhost:8000/reviews/master001.
Here there are.
And here there no any files.
As explained in the comments above, images should be in assets and static is only aimed for specific use cases, like exposing a publicly accessible .pdf file.
If you want to install and use jQuery properly into your Nuxt project, you can follow my answer here: https://stackoverflow.com/a/68414170/8816585
If you want to load a specific script and cannot do it in a more cleaner way (with NPM), you can also follow the instructions there: https://stackoverflow.com/a/67535277/8816585
Use this as a last resort tho and be aware that it will increase bundle size and loading time.

How to use static JS with Vue CLI?

I'm creating a Bootstrap Vue application (built with Vue CLI), and there's a Javascript library I want to be able to utilize: https://nadchif.github.io/html-duration-picker.js/. I tried putting the file in /assets and then using import in the script portion of App.vue (import './assets/html-duration-picker.min'), but I have not been able to get the script to work, not sure why (nothing happens, no duration picker shows). As an alternative, I thought I could maybe simply load the library in the traditional way in the head of index.html. But I'm not clear what the src URL should be for a file in the assets directory. Or should it be in the assets/public directory?
Honestly, you might as well use the npm package, if you are using Vue CLI, to save yourself a lot of trouble:
npm i html-duration-picker
DOCUMENTATION.md is where the installation instructions lie. While there aren't any for Vue, there are instructions for Angular, and it's fairly easy to get it working for Vue.
Just import html-duration-picker:
import * as HtmlDurationPicker from "html-duration-picker";
...and initalize it in mounted():
mounted() { HtmlDurationPicker.init() }
You can also run HtmlDurationPicker.refresh(); to "update dynamically loaded input boxes." I don't think this is necessary if you use v-model to bind the boxes' values to data properties which update fine from either end.
Here's a sandbox you can check out for more info.
If you do want to import it manually from assets, though, then what you're doing is probably fine (though you might need to add the .js to then end of the path); you'll just have to initialize it.

Vue-cli 3 Environment Variables all undefined

I've tried all of the solutions out there but none seem to work for me. I just want to store some values in a .env file within my Vue app but simply trying to log process.env returns an empty object from within the component.
My .env file
VUE_APP_URL={api url}
VUE_APP_TOKEN={token}
My plan was to set these environment variables to data properties but it always returns undefined. If I do console.log(process.env.NODE_ENV) from webpack.config.js it will show that I'm in development but if I tried doing the same from within the component like
mounted() {
this.$nextTick(() => {
console.log(process.env.VUE_APP_URL);
})
}
It just returns undefined.
A few tips for people who land here:
Make sure your .env files are in the project root folder (and not in say src/)
Variable names should start with VUE_APP_ if to be statically embedded into the client bundle
Restart the dev server or build your project for changes to take effect
If you are migrating from a webpack based solution make sure that you replace : (from JSON config) with = (dotenv format). Easy to miss
Make sure you've saved any changes to your .env files.
In old Vue versions environment variables were defined in e.g. config/dev.env.js instead of the .env files in root
I figured it out - I had to install dotenv-webpack and initialize it in webpack.config.js which is odd because none of the docs stated that I needed to do so.
Install dotenv-webpack and configure the vue.config.js file as follows.
npm install dotenv-webpack --save-dev
Add this to your config file:
const Dotenv = require('dotenv-webpack');
module.exports = {
configureWebpack: {
plugins: [
new Dotenv()
]
}
}
In your .env file make sure you add VUE_APP_ before your variables like this:
VUE_APP_VAR1=example
VUE_APP_VAR2=value
Now you can access these variables in your Vue application:
console.log(process.env.VUE_APP_VAR1); // "example"
console.log(process.env.VUE_APP_VAR2); // "value"
Here some links for reference:
https://www.npmjs.com/package/dotenv-webpack
https://cli.vuejs.org/guide/webpack.html
https://cli.vuejs.org/guide/mode-and-env.html#environment-variables
so I use
VUE_APP_API_URL (this doesn't work)
then I change it to
VUE_APP_APIURL (this works)
hope it helps
If your vue-cli version is higher than 3.x and you put your .env files in root directory like said in comments. Than you can access your environmental variables from components (like this process.env.VUE_APP_YOUR_VARIABLE).
As said in vue-cli docs
Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access
them in your application code: console.log(process.env.VUE_APP_SECRET)
I put my .env file in the root directory and appended each variable with VUE_APP_.
To demonstrate this, for example, if the variable you want to use is API_BASE_URL
In your .env file, you put the variable as VUE_APP_API_BASE_URL=baseurl/api/v1
To access it in your files, you do process.env.VUE_APP_API_BASE_URL.
CAVEAT:
Never put any sensitive information you don't want anybody to see, on your front-end. The most common thing you won't want anybody to see (as regards web development) is your API Key. There are real consequences to doing this. This is one such example of someone who has been burned exposing API keys to the public.
However, even if you put your sensitive data in a .env file and add the .env file to a .gitignore file (hence not pushing it to a Git repository hosting service e.g Github, BitBucket, Gitlab etc.), your data is still not safe on the front-end. It's only safe when this is done on back-end code as it will be hosted on a server.
In the front-end, anyone who is determined enough can find your sensitive information. All your information is available on a browser and all that person needs to do is to open the dev tools and check the Sources tab, and BOOM all your sensitive information is laid bare.
Environment variables on the front-end are only useful when you want one reference point for NON-SENSITIVE information, such as a BASE URL, as seen in the example above. A BASE URL can change during the course of development and you won't want to change all references in the application folder manually. It is tedious plus you may miss a few, which would lead to errors.
If you want to avoid exposing your API keys and other sensitive information you may require on the front-end, take a look at this article.
This is what worked for me. I previously created my .env.development and .env.production files in the root folder by manually by right-clicking in the Exploer in VS Code and adding a new file. This kept giving me undefined.
I deleted the files and first installed npm install touch-cli -g
Once installed, i added the environment files as such touch .env.production and touch .env.productionand itworks. So I think there's a difference between how these env files are generated.
NOTE: I do not have webpack installed. Just using the vue cli to build
VS Code ExplorerChrome Developer Tools
IF you are using VITE, use VITE_ in stead of VUE_APP
Vue CLI dotenv usage suffers the inability to provide the .env variables other than prefixed with VUE_APP_. This is OK but this is far not enough to satisfy any even little serious web project that wants to conveniently and securely manage its (sometimes huge) list of variables for different environments.
Here is the solution that makes use of .env variables as convenient as on backends with dotenv.
With this solution you could access your MY_EXTERNAL_API_KEY from your .env[.environment] file in your code like this const key = process.env.MY_EXTERNAL_API_KEY.
It provides:
The convenience of using non-prefixed with VUE_APP_ variables' names and use .env variable expansion feature (use ${VARNAME} kind of variables)
The necessary security: your variables are neither available at browser console with console.log(pocess.env.MYVAR) at run time nor are explorable via text search by their names from .env files within the built application's JS bundle.
You can still use original Vue CLI solution along;
For this use dotenv-webpack plugin in your vue.config.js as follows:
const Dotenv = require('dotenv-webpack');
const envPath = function() {
return (!process.env.NODE_ENV || (process.env.NODE_ENV === 'development')) ?
'./.env' :
`./.env.${process.env.NODE_ENV}`;
}
const dotenvArgs = {
expand: true,
path: envPath()
};
module.exports = {
//... some other config here
configureWebpack: {
plugins: [
new Dotenv(dotenvArgs)
]
}
};
Here:
expand: true allows for ${MYVAR} variables expansion;
path: envPath() allows to define custom .env file name depending on your Vue CLI project environments, and the path depending on you project structure;
There are other useful dotenv-webpack options you could use.
I believe this solution is good enough to fully satisfy most frequent use cases.
NB: Remember as you pass your secret variables set via .env into HTTP requests from your front-end (e.g. an API key in a call to some external API) they are visible to any one who knows where to look. To diminish security risks for this situation there are different solutions.
Just to hint you have either to:
provide only publicly open data via your application;
or authenticate your application (or parts of it) via some authentication service (login/password + JWT|sessions, external authentication providers e.g. Facebook, Google etc.);
or resort to server-generated application.
But this is the whole separate subject.
if you are cominng from VUE-cli-2 or you just cloned/installed an old vuejs project and you can't find .env file, this article explains what you have to do to set your .env variables as they environment files are probably located in config/dev.env.js (Note: this is peculiar to Vue-cli-2 files)
Here is also a solution and a detailed explanation for Vue-cli-3 .env related issue
What worked for me was changing from .env to .env.local. Haven't investigated WHY but I checked an old project and saw that I had a .env.local instead and did same for this project that would not pick the values from .env irrespective of whether vars where prefixed with VUE_APP and it worked.
It seems environment variables are not accessible in child Vue components. Best to declare them globally in main.js with Vue.prototype.env = process.env;
I know that this question was asked about vue-cli 3, which generates code for Vue 2. But it is the top result if you google for "vue3 does not embed env" and similar queries, so I assume that a lot of people end up here when having trouble with process.env variables being undefined in their Vue 3 app.
So this is an answer about how to fix your Vue 3 env issues.
This is what causes the confusion
If you google for env problems with vue, you end up in the vue-cli docs. But vue-cli was replaced by create-vue in Vue 3. There is a alert box at the top of the page that tells you this, but you've probably missed it.
If you did not miss it and followed one of the two links in the box, you ended up in the Vue 3 tooling guide or in the create-vue repo. None of those resources mention env variables. But you learn that create-vue is based on Vite.
If you follow that lead and google for "vite env", you end up in the vite documentation, where you finally find the answer:
env variables have to be prefixed with VITE_ to be compiled into the app (as opposed to VUE_APP_ in vue 2)
env variables will be available in import.meta.env in your app (as opposed to process.env in vue 2)
The latter one is what took me the longest to figure out.
This is how you need to do it
in an .env file in your project root:
VITE_MY_ENV_VAR=foo
The docs will also tell you about the different naming patterns for .env files in Vite. Very useful information if you work with different environments!
in your app:
const my_env_var = import.meta.env.VITE_MY_ENV_VAR
I hope this saves someone the time for figuring this out.
It might also help: make sure your .env files are in lowercase letters because in Linux it won't work even if it is working in windows
The answer provided here helped me out. I'm using Laravel with an odd setup for Vue 2.x. The project is also using Laravel Mix. Here's the solution:
Inside of your .env file, which is a sibling of package.json:
MY_ENVIRONMENT_VARIABLE=my_value
Inside of webpack.mix.js:
const { mix } = require('laravel-mix');
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.EnvironmentPlugin (
['MY_ENVIRONMENT_VARIABLE']
)
]
};
});
Afterwards, an npm run dev or npx mix should allow you to use these variables.
Credit: Thorsten Lünborg

Aurelia Element Loading Issues

Our environment has setup a private git repository and configured jspm to install packages from this repository. The repo has a .js, .html, and .css file. Jspm brings all the files down into a folder with #master appended to the name to reflect the branch and stores it all in the pre-configured jspm_packages location on my machine. It also adds a second #master.js file next to the folder with export statements inside (I didn't create this file myself).
These files represent custom elements I want to use in my aurelia application. There is a .js for the viewmodel and a .html for the view (and a .css file). When I go to use the custom element I get a 404, file not found, because system.js is looking for a #master.html file, which doesn't exist.
Jspm seems to be referencing the #master.js file in config.js and somehow that's assuming a #master.html file in Aurelia? Only a #master.js file was created when I installed the package using jspm. The original .html file does exist and lives inside the folder I mention above, but that #master.html file does not and I'm not sure 1) what that file would be for and 2) why it's being referenced. There no reference to #master.html in my code.
I'm not really even sure if this is a JSPM issue, Aurelia issue, System.js issue, or some combination of them?
Anyone else have a similar experience with these technologies?
Thanks,
Chris
Essentially, Aurelia believes you are importing your repo as a custom element, so when you are importing the #master.js it is looking for the matching "view" of what it assumes is a viewmodel.
It sounds like you need to structure your repository as a plugin. Add an index.js file at the top level and make that responsible for running the configure function, which should make the components you want global resources. Ensure your package.json points to your index.js as the 'main'. After that, you would need to add a .plugin('your-package-name') in the main.js file, just like any other plugin.
An example index.js is like so:
import {Options, GLOBAL_OPTIONS, DIRECTION} from './options';
import {Dragula} from './dragula';
import {moveBefore} from './move-before';
export {Dragula, Options, DIRECTION, moveBefore};
export function configure(config, callback) {
let defaults = new Options();
config.container.registerInstance(GLOBAL_OPTIONS, defaults);
if (callback !== undefined && typeof callback === 'function') {
callback(defaults);
}
config.globalResources(['./dragula-and-drop']);
}
(taken from here)