vue.jswebpackvuejs3vue-cli

vue cli environment variables


In webpack, I was able to set environment variables in my package.json like so:

"scripts": {
  "dev:visualise": "webpack serve --open --config webpack.dev.js --env entry=visualise",
  "dev:order": "webpack serve --open --config webpack.dev.js --env entry=order"
}

And then depending on which script I ran, I could access the environment var in my webpack config by doing:

module.exports = (env, argv) => merge(common, {
    entry: `./src/_sites/${env.entry}/index.ts`,
}

Is this possible with vue-cli?

I've tried getting it from process.env.entry

module.exports = defineConfig({
  chainWebpack: config => {
    console.log(process.env.entry);  // this is undefined
  },

or changing the module exports to

module.exports = env => defineConfig({
  chainWebpack: config => {
    console.log(env.entry);  // env is undefined
  },

but neither of these worked. Is it possible to get the env.entry variable in the vue config? Or is there a different way to only build specific entry points (or pages in vue.config - something like below)?

pages: {
    main: `Vue/Components/${process.env.entry}/main.ts`
},

Solution

  • Ok thanks to the comment from oshell, I was able to change my build to

    "build:dev-visualise": "vue-cli-service build --mode dev-visualise",
    

    then I created a file .env.dev-visualise and inside that file I could create my environment variables:

    ENTRY=visualise
    NODE_ENV=development
    

    Which I could then use in my vue.config:

    pages: {
        main: `Vue/Components/${process.env.ENTRY}/main.ts`
    },