skip to Main Content

How to get the root path of the Vue project from the browser when running npm run serve

eg: the path E:myApp

Thanks in advance

I’v tried these:

  1. process.cwd() but got /.
  2. require.resolve but got webpack error MODULE_NOT_FOUND
  3. __dirname and path.resolve(__dirname) return /

The Vue verison is ^3.2.37 and I use Vue CLI.

2

Answers


  1. It’s more a node problem, you can use:

    import path from "path";
    const absolutePath = path.resolve(__dirname);
    console.log(absolutePath);
    
    Login or Signup to reply.
  2. You could always define a computed environment variable in your vue.config.js file

    // vue.config.js
    process.env.VUE_APP_ROOT_PATH = __dirname;
    
    module.exports = {};
    

    Then in your app you can reference the environment variable

    export default {
      data: () => ({ rootPath: process.env.VUE_APP_ROOT_PATH })
    }
    

    Note that this value will be fixed and never change once you build your app.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search