How to generate Graphql types for React with help of graphql-codegen when Apollo Server is in production mode? - node.js

When backend mode set to NODE_ENV: development all works perfectly, but in production mode graphql-codegen fails with error:
Local web-server error:
GraphQL introspection is not allowed by Apollo Server, but the query
contained _schema or _type. To enable introspection, pass
introspection: true to ApolloServer in production
Production web-server error:
Failed to load schema from https://example.com/graphql, reason: unable
to verify the first certificate. GraphQL Code Generator supports:
ES Modules and CommonJS exports (export as default or named export "schema")
Introspection JSON File
URL of GraphQL endpoint
Multiple files with type definitions (glob expressions)
String in config file
Front-end codegen.yml:
schema: ${REACT_APP_GRAPHQL_URL}
documents:
- './src/GraphQL/queries/query.ts'
- './src/GraphQL/mutations/mutation.ts'
overwrite: true
generates:
./src/generated/graphql.tsx:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
config:
skipTypename: false
withHooks: true
withHOC: false
withComponent: false
Front-end devDependencies:
{
"#graphql-codegen/cli": "^1.20.1",
"#graphql-codegen/typescript": "^1.20.2",
"#graphql-codegen/typescript-operations": "^1.17.14",
"#graphql-codegen/typescript-react-apollo": "^2.2.1",
}
npm scripts:
{
"generate": "graphql-codegen -r dotenv/config --watch --config codegen.yml",
"prebuild": "graphql-codegen -r dotenv/config --config codegen.yml"
}
./src/generated/ directory added to .gitignore

My solution was in add introspection plugin and separate codegen.yml file into:
codegen-generate-schema-json and
codegen-generate-typescript
devDependencies: {"#graphql-codegen/introspection": "^1.18.1"}
codegen-generate-typescript.yml:
schema: graphql.schema.json
documents:
- './src/GraphQL/queries/query.ts'
- './src/GraphQL/mutations/mutation.ts'
overwrite: true
generates:
./src/generated/graphql.tsx:
plugins:
- typescript
- typescript-operations
- typescript-react-apollo
config:
skipTypename: false
withHooks: true
withHOC: false
withComponent: false
codegen-generate-schema-json.yml:
schema: ${REACT_APP_GRAPHQL_URL}
overwrite: true
generates:
./graphql.schema.json:
plugins:
- introspection
So ./graphql.schema.json file need to be commited and used as schema source instead of URI.
Maybe you suggest the better solution?

Related

Webpack error after upgrading Node: "Module parse failed: Unexpected token"

I'm troubleshooting a webpack error.
Command: bin/webpack --colors --progress
Produces this error:
ERROR in ./node_modules/#flatfile/sdk/dist/index.js 351:361
Module parse failed: Unexpected token (351:361)
File was processed with these loaders:
* ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| class v extends i {
| constructor(e, t) {
> super(e), r(this, "code", "FF-UA-00"), r(this, "name", "UnauthorizedError"), r(this, "debug", "The JWT was not signed with a recognized private key or you did not provide the necessary information to identify the end user"), r(this, "userMessage", "There was an issue establishing a secure import session."), e && (this.debug = e), this.code = t ?? "FF-UA-00";
| }
| }
# ./app/javascript/src/app/pages/content_assets/Index.vue?vue&type=script&lang=ts& (./node_modules/babel-loader/lib??ref--8-0!./node_modules/vue-loader/lib??vue-loader-options!./app/javascript/src/app/pages/content_assets/Index.vue?vue&type=script&lang=ts&) 22:0-41 125:6-14
# ./app/javascript/src/app/pages/content_assets/Index.vue?vue&type=script&lang=ts&
# ./app/javascript/src/app/pages/content_assets/Index.vue
# ./app/javascript/packs/app.js
NOTES
I found what appears to be an identical issue reported in the Flatfile project: https://github.com/FlatFilers/sdk/issues/83
Looks like ES2020 was emitted to the /dist folder so my cra babel loader is not able to parse it, in order to fix it I need to include the path on my webpack config.
Node v16.13.1
We're using webpack with a Rails project via the webpacker package (#rails/webpacker": "5.4.3") which is depending on webpack#4.46.0.
When I change to Node v14x and rebuild node_modules (yarn install) webpack compiles successfully.
The line referenced in the error (351:361) does not exist when I go check the file in node_modules/
We have a yarn.lock file, which I delete and recreate before running yarn install. I also delete the node_modules directory to ensure a "fresh" download of the correct packages.
We have a babel.config.js file...
module.exports = function(api) {
var validEnv = ['development', 'test', 'production']
var currentEnv = api.env()
var isDevelopmentEnv = api.env('development')
var isProductionEnv = api.env('production')
var isTestEnv = api.env('test')
if (!validEnv.includes(currentEnv)) {
throw new Error(
'Please specify a valid `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(currentEnv) +
'.'
)
}
return {
presets: [
isTestEnv && [
'#babel/preset-env',
{
targets: {
node: 'current'
}
}
],
(isProductionEnv || isDevelopmentEnv) && [
'#babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'entry',
corejs: 3,
modules: false,
exclude: ['transform-typeof-symbol']
}
],
["babel-preset-typescript-vue", { "allExtensions": true, "isTSX": true }]
].filter(Boolean),
plugins: [
'babel-plugin-macros',
'#babel/plugin-syntax-dynamic-import',
isTestEnv && 'babel-plugin-dynamic-import-node',
'#babel/plugin-transform-destructuring',
[
'#babel/plugin-proposal-class-properties',
{
loose: true
}
],
[
'#babel/plugin-proposal-object-rest-spread',
{
useBuiltIns: true
}
],
[
'#babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true,
corejs: false
}
],
[
'#babel/plugin-transform-regenerator',
{
async: false
}
]
].filter(Boolean)
}
}
Ultimately I want to get webpack to compile. If you had advice about any of the following questions, it would help a lot.
Why would changing the Node version (only) cause different webpack behavior? We aren't changing the the webpack version or the version of the #flatfile package that's causing the error.
Why is the error pointing to a line that doesn't exist in the package? Is this evidence of some kind of caching problem?
Does the workaround mentioned in the linked GitHub issue shed light on my problem?
I'll take a stab at this.
I believe your issue is that webpack 4 does not support the nullish coalescing operator due to it's dependency on acorn 6. See this webpack issue and this PR comment.
You haven't specified the exact minor version of Node.js 14x that worked for you. I will assume it was a version that did not fully support the nullish coalescing operator, or at least a version that #babel/preset-env's target option understood to not support ??, so it was transpiled by babel and thus webpack didn't complain. You can see what versions of node support nullish coalescing on node.green.
I don't fully understand the point you are making here, so not focusing on this in the proposed solution.
I'm not sure what the proposed workaround is in the linked issue, maybe the comment about "include the path on my webpack config", but yes the issue does seem relevant as it is pointing out the nullish coalescing operator as the source of the issue.
You can try to solve this by
adding #babel/plugin-proposal-nullish-coalescing-operator to your babel config's plugins
updating your webpack config to run #flatfile/sdk through babel-loader to transpile the nullish coalescing operator:
{
test: /\.jsx?$/,
exclude: filename => {
return /node_modules/.test(filename) && !/#flatfile\/sdk\/dist/.test(filename)
},
use: ['babel-loader']
}
Another possibility is to upgrade webpacker to a version that depends upon webpack v5.
One final remark, when you say
We have a yarn.lock file, which I delete and recreate before running yarn install.
you probably should not be deleting the lock file before each install, as it negates the purpose of a lock file altogether.

My React App Unit Tests Jest is breaking: function(module,exports,require,__dirname,__filename,jest) Cannot use import statement outside a module

I'm facing a problem when trying to run the Jest tests (NextJs app) with my component library.
My React library
I'm using this command to build the React library:
"build-esm": "tsc --project tsconfig.build.json",
"build-cjs": "tsc --project tsconfig.build.json --module commonjs --outDir lib/cjs",
"build": "rm -fr lib/ && npm run build-esm && npm run build-cjs"
Will generate it:
package.json:
(...)
"main": "./lib/cjs/index.js",
"module": "./lib/esm/index.js",
"types": "./lib/esm/index.d.ts",
(...)
My "Nextjs client project" (that will use the lib as a dependency):
jest.config.js
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './'
});
// Add any custom config to be passed to Jest
/** #type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
setupFilesAfterEnv: ['./jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules'],
testEnvironment: 'jest-environment-jsdom',
transformIgnorePatterns: ['<rootDir>/node_modules/']
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
console error:
(...)/node_modules/nanoid/index.browser.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { urlAlphabet } from './url-alphabet/index.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
8 | var react_window_1 = require("react-window");
9 | var react_window_infinite_loader_1 = __importDefault(require("react-window-infinite-loader"));
> 10 | var nanoid_1 = require("nanoid");
I appreciate any support

jest.config.ts: "registerer.enabled is not a function" error when running jest from Github Actions

When running jest locally, it instantiates my app and runs tests without any issues.
When running jest inside github actions, I'm getting this error:
Error: Jest: Failed to parse the TypeScript config file /home/runner/work/myproject/myproject/jest.config.ts
TypeError: registerer.enabled is not a function
at readConfigFileAndSetRootDir (/home/runner/work/myproject/myproject/node_modules/#jest/core/node_modules/jest-config/build/readConfigFileAndSetRootDir.js:118:13)
the package.json script entry is just:"test": "jest"
and the jest.config.ts file is:
import tsJestUtils from 'ts-jest/utils'
import tsConf from './tsconfig.json'
const rootDir = __dirname
const { pathsToModuleNameMapper } = tsJestUtils
const {
compilerOptions: { paths },
} = tsConf
const config = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: [`${rootDir}/src`],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
moduleNameMapper: pathsToModuleNameMapper(paths, {
prefix: `${rootDir}/src`,
}),
}
export default config
So I just bypassed use of typescript for my jest config entirely, and went with an equivalent jest.config.js file based on the docs. Works in Github Actions now, runner does not fail! \o/
I am still not sure what the issue was, but I think ts-node just wasn't processing the config file properly. I feel like the actual failure was with the attempt to load a .ts config file, specifically at this point in the source code when it tries to call registerer.enabled().
It can be fixed by upgrading to "ts-node": "^8.5.0"

"Cannot use import statement outside a module" in typeorm migration when run nestjs app

I have created the nestjs app. In the root app folder I have these subfolders:
dist
migration
src
test
The migration folder contains typeorm migrations.
When run application with npm run start:dev I have this error:
import {MigrationInterface, QueryRunner} from "typeorm";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Module._compile (internal/modules/cjs/loader.js:891:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Function.PlatformTools.load (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\platform\PlatformTools.js:114:28)
at C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:69
at Array.map (<anonymous>)
at Object.importClassesFromDirectories (C:\Users\dakru1\Documents\employo\employo-api\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:39:10)
I understand the error message and I know how to fix it when it relates to application's code.
However, my problem is that this error come from typeorm migration file: [app-root-folder]\migration\1587067680466-Init.ts which shouldn't be used when application runs.
Why nestjs uses migration files. How can I ignore migration folder when running nestjs app?
to solve it just put the following code on your "scripts" at package.json:
"typeorm": "ts-node-dev ./node_modules/typeorm/cli.js",
After that you'll be able to run your typeorm migration:run :)
I found the solution:
This happends to me because I was using Nest and when you run the command nest start, under the hood, Nest executes node and tsc and node commands and because of that you need your files to be in JavaScript format. So, as the migrations are generated in Typescript... the statement import gives the error because is only for TypeScript.
The only thing i did to solve it is this:
migrations: ["dist/migrations/*.js"],
This is telling TypeOrm that search for the migration in the dist directory where all the JavaScript code was compiled previously.
Of course in my tsconfig.json file the output dir is pointing to dist.
"outDir": "./dist",
I had the same issue. I did the following as a workaround:
Set your ormconfig.json to look for migrations files with only js suffix:
"migrations": ["migrations/*.js"],
Install typescript globally: npm install -g typescript
After generating your migration, transpile typescript files to javascript files with typescript command:
tsc migrations/migration-file.ts
Run your migration: npm run typeorm migration:run
You can now run your application: npm run start:dev
I know this question is old, but I just came across it because I had the same problem. I was able to solve it by adding "migration/**/*.ts" to the "exclude" array in the /tsconfig.build.json file like so:
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts", "migration/**/*.ts"]
}
The same issue here, and in my case the root cause was a wrong migrations path in the connection configuration, like this;
const databaseConfig: ConnectionOptions = {
name: 'default',
type: 'postgres',
host: process.env.TYPEORM_HOST || '',
port: Number(process.env.TYPEORM_PORT),
username: process.env.TYPEORM_USERNAME || '',
password: process.env.TYPEORM_PASSWORD || '',
database: process.env.TYPEORM_DATABASE || '',
logging: false,
synchronize: false,
entities: [],
migrations: ['src/migrations/*.ts'],
};
Instead, I have changed it to
const migrationPaths: string[] = process.env.TYPEORM_USE_CLI === 'true' ? ['src/migrations/*{.ts,.js}'] : [];
const databaseConfig: ConnectionOptions = {
name: 'default',
type: 'postgres',
host: process.env.TYPEORM_HOST || '',
port: Number(process.env.TYPEORM_PORT),
username: process.env.TYPEORM_USERNAME || '',
password: process.env.TYPEORM_PASSWORD || '',
database: process.env.TYPEORM_DATABASE || '',
logging: false,
synchronize: false,
entities: [],
migrations: migrationPaths,
};
another test you can try to see if the problem is really with migration is to move the migration filter out of src.
For TypeORM v0.3.0 or higher, glob patterns in migrations are DEPRECATED. It is recommended to directly include the migration classes.
entities, migrations, subscribers options inside DataSourceOptions accepting string directories support is deprecated. You'll be only able to pass entity references in the future versions.
import { DataSource, DataSourceOptions } from 'typeorm';
import { CreateUser1669370712331 } from '../../migrations/1669370712331-CreateUser';
import { UserModify1669457039074 } from '../../migrations/1669457039074-UserModify';
import { User } from '../users/entities/user.entity';
export const config: DataSourceOptions = {
type: 'sqlite',
database: 'db/database.sqlite',
logging: true,
synchronize: false,
entities: [User],
migrations: [CreateUser1669370712331, UserModify1669457039074],
};

Using Environment Variables with Vue.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

Resources