While constructing a Vue (2.7.14) component with webpack-dev-server, I encountered a need to make a URL dynamic in my Vue CLI 2 code using a process.env variable. In order to achieve this, I made a modification to the line of code in MyComponent.vue
:
const uploadUrl = `http://localhost:3000/api/mycall`;
and transformed it into this:
const uploadUrl = `${process.env.VUE_APP_APIURL}/api/mycall`;
(Side Note: Initially, I faced an issue where webpack was not updating. Since the process.env variable value was the same as the one used in the hard-coded version, I mistakenly believed it was functioning properly until much later. It was only upon closer inspection that I noticed the actual text change - specifically ${process.env.VUE_APP_APIURL}
- in the browser code. After investigating further, I realized that webpack-dev-server was concealing the build problem by removing the error from the screen. Upon discovering that webpack was not updating, I checked my terminal and found a 'DONE Compiled successfully' message displaying. Possibly related to this. Argh!)
Subsequent to implementing the aforementioned change, I began to encounter webpack compilation errors such as these:
15% building modules 49/58 modules 9 active .../src/components/MyComponent.vue
SyntaxError: Unexpected token (1:5)
at Parser.pp$4.raise (/Users/darrin/src/applet/node_modules/acorn-dynamic-import/node_modules/acorn/dist/acorn.js:2488:13)
at Parser.pp.unexpected (/Users/darrin/src/applet/node_modules/acorn-dynamic-import/node_modules/acorn/dist/acorn.js:623:8)
at Parser.pp.expect (/Users/darrin/src/applet/node_modules/acorn-dynamic-import/node_modules/acorn/dist/acorn.js:617:26)
at Parser.pp$3.parseParenAndDistinguishExpression (/Users/darrin/src/applet/node_modules/acorn-dynamic-import/node_modules/acorn/dist/acorn.js:2043:38)
at Parser.pp$3.parseExprAtom (/Users/darrin/src/applet/node_modules/acorn-dynamic-import/node_modules/acorn/dist/acorn.js:1978:41)
Below is the configuration for dev.env.js
where the variable value is defined:
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
VUE_APP_APIURL: 'http://localhost:3001'
})