Using Environment Variables with Vue.js - node.js

I've been reading the official docs and I'm unable to find anything on environment variables. Apparently there are some community projects that support environment variables but this might be overkill for me. So I was wondering if there's something simple out of the box that works natively when working on a project already created with Vue CLI.
For example, I can see that if I do the following the right environment prints out meaning this is already setup?
mounted() {
console.log(process.env.ROOT_API)
}
I'm a kinda new to env variables and Node.
FYI using Vue CLI version 3.0 beta.

Vue.js with Webpack
If you use vue cli with the Webpack template (default config), you can create and add your environment variables to a .env file.
The variables will automatically be accessible under process.env.variableName in your project. Loaded variables are also available to all vue-cli-service commands, plugins and dependencies.
You have a few options, this is from the Environment Variables and Modes documentation:
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
Your .env file should look like this:
VUE_APP_MY_ENV_VARIABLE=value
VUE_APP_ANOTHER_VARIABLE=value
As noted in comment below:
If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.
Don't forget to restart serve if it is currently running.
Vue.js with Vite
Vite exposes env variables that start with VITE_ on the special import.meta.env object.
Your .env should look like this:
VITE_API_ENDPOINT=value
VITE_API_KEY=value
These variables can be accessed in Vue.js components or JavaScript files under import.meta.env.VITE_API_ENDPOINT and import.meta.env.VITE_API_KEY.
Tip: Remember to restart your development server whenever you change or add a variable in the .env file if it's running.
For more info, please see the Vite documentation for env variables.

If you are using Vue cli 3, only variables that start with VUE_APP_ will be loaded.
In the root create a .env file with:
VUE_APP_ENV_VARIABLE=value
And, if it's running, you need to restart serve so that the new env vars can be loaded.
With this, you will be able to use process.env.VUE_APP_ENV_VARIABLE in your project (.js and .vue files).
Update
According to #ali6p, with Vue Cli 3, isn't necessary to install dotenv dependency.

Create two files in root folder (near by package.json) .env and .env.production
Add variables to theese files with prefix VUE_APP_ eg: VUE_APP_WHATEVERYOUWANT
serve uses .env and build uses .env.production
In your components (vue or js), use process.env.VUE_APP_WHATEVERYOUWANT to call value
Don't forget to restart serve if it is currently running
Clear browser cache
Be sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html

In the root of your project create your environment files:
.env
.env.someEnvironment1
.env.SomeEnvironment2
To then load those configs, you would specify the environment via mode i.e.
npm run serve --mode development //default mode
npm run serve --mode someEnvironment1
In your env files you simply declare the config as key-value pairs, but if you're using vue 3, you must prefix with VUE_APP_:
In your .env:
VUE_APP_TITLE=This will get overwritten if more specific available
.env.someEnvironment1:
VUE_APP_TITLE=My App (someEnvironment1)
You can then use this in any of your components via:
myComponent.vue:
<template>
<div>
{{title}}
</div>
</template>
<script>
export default {
name: "MyComponent",
data() {
return {
title: process.env.VUE_APP_TITLE
};
}
};
</script>
Now if you ran the app without a mode it will show the 'This will get...' but if you specify a someEnvironment1 as your mode then you will get the title from there.
You can create configs that are 'hidden' from git by appending .local to your file: .env.someEnvironment1.local - very useful for when you have secrets.
Read the docs for more info.

A problem I was running into was that I was using the webpack-simple install for VueJS which didn't seem to include an Environment variable config folder. So I wasn't able to edit the env.test,development, and production.js config files. Creating them didn't help either.
Other answers weren't detailed enough for me, so I just "fiddled" with webpack.config.js. And the following worked just fine.
So to get Environment Variables to work, the webpack.config.js should have the following at the bottom:
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
Based on the above, in production, you would be able to get the NODE_ENV variable
mounted() {
console.log(process.env.NODE_ENV)
}
Now there may be better ways to do this, but if you want to use Environment Variables in Development you would do something like the following:
if (process.env.NODE_ENV === 'development') {
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
}
})
]);
}
Now if you want to add other variables with would be as simple as:
if (process.env.NODE_ENV === 'development') {
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"',
ENDPOINT: '"http://localhost:3000"',
FOO: "'BAR'"
}
})
]);
}
I should also note that you seem to need the "''" double quotes for some reason.
So, in Development, I can now access these Environment Variables:
mounted() {
console.log(process.env.ENDPOINT)
console.log(process.env.FOO)
}
Here is the whole webpack.config.js just for some context:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
if (process.env.NODE_ENV === 'development') {
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"',
ENDPOINT: '"http://localhost:3000"',
FOO: "'BAR'"
}
})
]);
}

This is how I edited my vue.config.js so that I could expose NODE_ENV to the frontend (I'm using Vue-CLI):
vue.config.js
const webpack = require('webpack');
// options: https://github.com/vuejs/vue-cli/blob/dev/docs/config.md
module.exports = {
// default baseUrl of '/' won't resolve properly when app js is being served from non-root location
baseUrl: './',
outputDir: 'dist',
configureWebpack: {
plugins: [
new webpack.DefinePlugin({
// allow access to process.env from within the vue app
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
})
]
}
};

In vue-cli version 3:
There are the three options for .env files:
Either you can use .env or:
.env.test
.env.development
.env.production
You can use custom .env variables by using the prefix regex as /^/ instead of /^VUE_APP_/ in /node_modules/#vue/cli-service/lib/util/resolveClientEnv.js:prefixRE
This is certainly not recommended for the sake of developing an open source app in different modes like test, development, and production of .env files. Because every time you npm install .. , it will be overridden.

In addition to the previous answers, if you're looking to access VUE_APP_* env variables in your sass (either the sass section of a vue component or a scss file), then you can add the following to your vue.config.js (which you may need to create if you don't have one):
let sav = "";
for (let e in process.env) {
if (/VUE_APP_/i.test(e)) {
sav += `$${e}: "${process.env[e]}";`;
}
}
module.exports = {
css: {
loaderOptions: {
sass: {
data: sav,
},
},
},
}
The string sav seems to be prepended to every sass file that before processing, which is fine for variables. You could also import mixins at this stage to make them available for the sass section of each vue component.
You can then use these variables in your sass section of a vue file:
<style lang="scss">
.MyDiv {
margin: 1em 0 0 0;
background-image: url($VUE_APP_CDN+"/MyImg.png");
}
</style>
or in a .scss file:
.MyDiv {
margin: 1em 0 0 0;
background-image: url($VUE_APP_CDN+"/MyImg.png");
}
from https://www.matt-helps.com/post/expose-env-variables-vue-cli-sass/

Important (in Vue 4 and likely Vue 3+ as well!): I set VUE_APP_VAR but could NOT see it by console logging process and opening the env object. I could see it by logging or referencing process.env.VUE_APP_VAR. I'm not sure why this is but be aware that you have to access the variable directly!

For those using Vue CLI 3 and the webpack-simple install, Aaron's answer did work for me however I wasn't keen on adding my environment variables to my webpack.config.js as I wanted to commit it to GitHub. Instead I installed the dotenv-webpack plugin and this appears to load environment variables fine from a .env file at the root of the project without the need to prepend VUE_APP_ to the environment variables.

I am having same problem in vuecli#5. Trying to solve by reading official doc but can't get proper solution. After long time i got solution and it works fine.
Create .env file on root dir. touch .env
Set value on it i.e APP_NAME=name
vue.config.js file past it process.env.VUE_APP_VERSION = require('./package.json').version
Log to any method console.log(process.env.APP_NAME);

Running multiple builds with different .env files 🏭
In my app I wanted to have multiple production builds, one for a web app, and another for a browser extension.
In my experience, changing build modes can have side effects as other parts of the build process can rely on being in production for example, so here's another way to provide a custom env file (based on #GrayedFox's answer):
package.json
{
"scripts": {
"build": "vue-cli-service build",
"build:custom": "VUE_CLI_SERVICE_CONFIG_PATH=$PWD/vue.config.custom.js vue-cli-service build",
}
}
vue.config.custom.js
// install `dotenv` with `yarn add -D dotenv`
const webpack = require("webpack");
require("dotenv").config({ override: true, path: "./.env.custom" });
module.exports = {
plugins: [new webpack.EnvironmentPlugin({ ...process.env })],
};
Note 1: VUE_CLI_SERVICE_CONFIG_PATH swaps out the config from the default of vue.config.js, so any settings set in there will not apply for the custom build.
Note 2: this will load .env.production before .env.custom, so if you don't want any of the environment variables set in .env.production in your custom build, you'll want to set those to a blank string in .env.custom.
Note 3: If you don't set override: true then environment variables in .env.production will take precedence over .env.custom.
Note 4: If you are looking to have multiple different builds using vue-cli, the --skip-plugins option is very useful.

**just install this **
npm install -g #vue/cli
at your project
it is worked with me

Related

Vite: Including files in build output

This is a Vue 3 + Vuetify + TS + Vite + VSCode project.
I'm trying to bundle an XML file in the production build. Some transformation needs to be applied on the file before spitting it out. Found this Vite plug-in that can do transformations. But unfortunately, it doesn't seem to touch XML files in any way. If I put my XML file in public folder, it gets copied to the build output, but is not processed by the transformation plugin. If I put it in assets or somewhere else under src, it is simply ignored.
How can I ask Vite to include certain file(s) in the build output and pass it through transformation?
Note: Before I migrated the project to Vite, I was using Vue 2 and WebPack, where I could use the well-known CopyWebpackPlugin to perform this transformation. Haven't been able to find locate its Vite equivalent till now.
You may want to just write a script to do the transformation and add it to your npm scripts. I created a simple chrome extension to play around with VITE. Having multiple html files was pretty simple:
import { defineConfig, BuildOptions } from 'vite'
import vue from '#vitejs/plugin-vue'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
popup: resolve(__dirname, 'popup/index.html'),
options: resolve(__dirname, 'options/index.html'),
},
}
}
})
But I had to create a separate vite config file to process the background script since it had special configuration (didn't want hashing so I could specify the name in my manifest, esm module format), and it takes the typescript and outputs 'background.js' in the public folder:
import { defineConfig } from 'vite'
const { resolve } = require('path')
// https://vitejs.dev/config/
export default defineConfig({
build: {
emptyOutDir: false,
rollupOptions: {
input: resolve(__dirname, 'background.ts'),
output: {
format: "esm",
file: "public/background.js",
dir: null,
}
}
}
})
You could simply have the xml file in your src folder and run a special script (create a 'scripts' folder maybe) to do the transform and store the result in the public folder where vite will pick it up and copy it to the dist folder. Your 'build' script in package.json could look something like this:
"scripts": {
"build": "node scripts/transform-xml.mjs && vite build",
},
Author of the package has introduced a new option named replaceFiles in the version 2.0.1 using which you can specify the files that will be passed through the transform pipeline. I can now do the following in my vite.config.js to replace variables in my output manifest.xml file after build:
const replaceFiles = [resolve(join(__dirname, '/dist/manifest.xml'))];
return defineConfig({
...
plugins: [
vue(),
transformPlugin({
replaceFiles,
replace: {
VERSION_NUMBER: process.env.VITE_APP_VERSION,
SERVER_URL: process.env.VITE_SERVER_URL,
},
...
}),
...
});

Vite library with Windicss

I am using Vite (Vue3) with Windi CSS to develop a library. I am using library mode for the build (https://vitejs.dev/guide/build.html#library-mode) with the following config:
vite.config.js
export default defineConfig({
plugins: [vue(), WindiCSS()],
build: {
lib: {
entry: path.resolve(__dirname, 'src/lib.js'),
name: 'MyLIB',
},
rollupOptions: {
// make sure to externalize deps that shouldn't be bundled
// into your library
external: ['vue'],
output: {
// Provide global variables to use in the UMD build
// for externalized deps
globals: {
vue: 'Vue',
},
},
},
},
});
My entry file (src/lib.js) only includes a few Vue components in it and looks like this:
lib.js
export { default as AButton } from './components/AButton/AButton.vue';
export { default as ACheckbox } from './components/ACheckbox/ACheckbox.vue';
import 'virtual:windi.css';
import './assets/fonts.css';
When I build the library I get the js for just those components but the css is for every Vue file in the src folder and not only the ones i included in my lib.js file. I know the default behavior for Windi CSS is to scan the whole src folder but in this case, I only want it to scan the components I added to my entry.
Any ideas?
You should be able to restrict the scan by using extract.include and extract.exclude options, see there : https://windicss.org/guide/extractions.html#scanning
From the doc
If you want to enable/disable scanning for other file-types or locations, you can configure it using include and exclude options

Node.js: How to import test files in custom test runner

I'm trying to create my own custom testing framework for learning purpose. Test files are written in following way
import { somemethod } from './some/module'
test(/I click on a button)/, () => {
browser.get("someSelector").should("have.text",somemethod());
});
I user require(file) to load test files. But it throw error SyntaxError: Unexpected token {
for import statement in test file. I'm using node js version 11.15.
If I switch to node v13.14 and define "type": "module" in my package.json then it doesn't let me use require(file) to load a test file or any module in my package.
How can I import tests files considering the user may be importing the modules using import or require?
This answer is very empirical...
Considering that it works using canonical commonjs approach you can try to debug it with newer version of NODE (currently I would use 14). For it, I would suggest you to use a node version manager like NVM so you can switch between node version easily and test that accordling seeing differences between various node installations.
Make a minimal project with npm init with a single dependency, save your index with the .mjs extension and try an import the above dependency. If you are be able to import that dependency with that minimal environment you can blame either your previous node or your configuration or both of them.
At the moment you should only create a small 2 files project to reproduce the problem. It seems your current node does not consider the "type": "module" configuration and runs everything in its classic way.
Regarding your comments....
As far as I know import can be used even in your code, not just at the beginning:
(async () => {
if (somethingIsTrue) {
// import module for side effects
await import('/modules/my-module.js');
}
})();
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Additionally you can try Webpack with a configuration like:
// webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
mode: 'production',
target: 'node',
externals: [nodeExternals()],
entry: {
'build/output': './src/index.js'
},
output: {
path: __dirname,
filename: '[name].bundle.js',
libraryTarget: 'commonjs2'
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: [
['env', {
'targets': {
'node': 'current'
}
}]
]
}
}
}]
}
};
With NodeExternals you don't put your node dependencies in the bundle but only your own code. You refer to node_modules for the rest. You might not want that.

compile typescript to js with webpack and keep directory structure

I want webpack to compile my typescript node project into js but I want it to maintain the directory structure and not bundle into 1 file.
Is this possible?
My structure is:
src
|_controllers
|_home
|_index.ts
|_ services
// etc.
And I want it to compile to:
dist
|_controllers
|_home
|_index.ts
|_ services
// etc.
currently my config is like this:
{
name: 'api',
target: 'node',
externals: getExternals(),
entry: isDevelopment ? [...entries] : entries,
devtool: !isDevelopment && 'cheap-module-source-map',
output: {
path: paths.appBuild,
filename: '[name].js',
libraryTarget: 'commonjs2'
},
plugins: [
new WriteFilePlugin(),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
}),
isProduction && new webpack.optimize.ModuleConcatenationPlugin()
]
}
Is it possible with webpack?
I can't use just tsc because I have a yarn workspaces monorepo and I might have a link reference like this:
import {something} from '#my/package';
#my/package does not exist in npm and only exists in the context of the monorepo, I can use node externals with webpack to include it in the bundle I don't think I can keep the folder structure this way.
Would the new typescript 3.0 project references solve this problem?
Understood your concerns. Looks it's completely doable by transpile-webpack-plugin. You may setup it as below:
const TranspilePlugin = require('transpile-webpack-plugin');
module.exports = {
// ...
entry: './src/controllers/home/index.ts',
output: {
path: __dirname + '/dist',
},
plugins: [new TranspilePlugin({ longestCommonDir: './src' })],
};
The plugin works well with webpack resolve.alias and externals. All the files directly or indirectly imported by the entry will be collected and compiled into the output dir seperately without bundling but with keeping the directory structure and file names. Just have a try. 🙂

How do I get the debugger to recognize the sourcemaps in webstorm 10 using the react starter kit

I created a sample react starter kit project in webstorm using webstorm's pre-defined project template and am trying to set breakpoints in debug mode.
I first built the project using npm run build then set the debug configuration to run build/server.js.
However it won't recognize any of the breakpoints in the original source files and seems to be ignoring the sourcemaps. How can I get it to recognize the sourcemaps and allow me to both set breakpoints in the source files as well as step into the source files.
There is this issue in the react starter kit repo: https://github.com/kriasoft/react-starter-kit/issues/121 but I couldn't see what the resolution was, and unlike the commenter, I couldn't even get it to step into the source files... it just stayed on the generated js files instead.
Well...
WebStorm 10 has no support for sourcemaps generated by Webpack. They are partially supported in WebStorm 11 for client-side applications (see http://blog.jetbrains.com/webstorm/2015/09/debugging-webpack-applications-in-webstorm/), but not supported for Node.js.
so, you can't debug server.js in WebStorm 11, but you can debug client side. To do this, try the following:
change appConfig in src/config.js as follows:
const appConfig = merge({}, config, {
entry: [
...(WATCH ? ['webpack-hot-middleware/client'] : []),
'./src/app.js',
],
output: {
path: path.join(__dirname, '../build/public'),
filename: 'app.js',
},
devtool: 'source-map',
module: {
loaders: [
WATCH ? {
...JS_LOADER,
query: {
// Wraps all React components into arbitrary transforms
// https://github.com/gaearon/babel-plugin-react-transform
plugins: ['react-transform'],
extra: {
'react-transform': {
transforms: [
{
transform: 'react-transform-hmr',
imports: ['react'],
locals: ['module'],
}, {
transform: 'react-transform-catch-errors',
imports: ['react', 'redbox-react'],
},
],
},
},
},
} : JS_LOADER,
...config.module.loaders,
{
test: /\.css$/,
loader: 'style-loader/useable!css-loader!postcss-loader',
},
],
},
});
set up the javascript debug run configuration:
URL: http://localhost:5000
Remote URLs: map project root folder to 'webpack:///path/to/react-starter-kit', like 'webpack:///C:/WebstormProjects/react-starter-kit'
map build/public to http://localhost:5000
This doesn't work perfectly, but works in general - breakpoints in src/routes.js, src/app.js are hit

Resources