Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to set alias #2398

Closed
YafXe opened this issue Aug 30, 2018 · 19 comments
Closed

how to set alias #2398

YafXe opened this issue Aug 30, 2018 · 19 comments

Comments

@YafXe
Copy link

YafXe commented Aug 30, 2018

What problem does this feature solve?

what should i do when i need to set a alias like '@' same as 'src' ?

What does the proposed API look like?

i need cli-2.0 resolve setting

@sirlancelot
Copy link
Contributor

You can add it to the Webpack config by placing your aliases in the vue.config.js file as shown here: https://cli.vuejs.org/guide/webpack.html#simple-configuration

@haoqunjiang
Copy link
Member

GitHub issues are for bug reports & feature requests only.
Next time please consider using forums for questions: https://forum.vuejs.org/c/chinese


Such aliases are already set.

.alias
.set('@', api.resolve('src'))

You can use configureWebpack or chainWebpack in vue.config.js to set your own aliases.

@komali2
Copy link

komali2 commented Oct 16, 2018

@sirlancelot

Your solution doesn't appear to work:

vue.config.js

const path = require('path');
module.exports = {
    resolve: {
        alias: {
            '@': path.join(__dirname, 'client/src/')
        }
    }
}

Error:

ERROR Invalid options in vue.config.js: "resolve" is not allowed

vue.config.js

const path = require('path');
module.exports = {
    alias: {
        '@': path.join(__dirname, 'client/src/')
    }
}

Error:

ERROR Invalid options in vue.config.js: "alias" is not allowed

@sodatea that solution doesn't work, my files are separated into a client/ and api/ folder, and I have to launch the cli with a custom entrypoint in the commandline, like so:

"serve:ui": "vue-cli-service serve client/src/main.js",

@komali2
Copy link

komali2 commented Oct 16, 2018

Context option also doesn't work

vue.config.js

const path = require('path');
module.exports = {
    context: path.resolve(__dirname, './client'),
}

ERROR Invalid options in vue.config.js: "context" is not allowed

@komali2
Copy link

komali2 commented Oct 16, 2018

Seems the solution is something along the lines of:

vue.config.js

const path = require('path')
module.exports = {
    chainWebpack: config => {
        config.resolve.alias
            .set('@', path.resolve(__dirname, 'client/src'));
  }
}

as per

https://cli.vuejs.org/guide/webpack.html#chaining-advanced

https://forum.vuejs.org/t/vue-cli-3-0/39055/6

@ajcastro
Copy link

This works

// vue.config.js
const path = require('path');
module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        "~": path.resolve(__dirname, 'src/')
      }
    }
  }
}

@jpcbdev
Copy link

jpcbdev commented May 16, 2019

If you use vue create cli just use '@/...' by default this resolve the path ./src, so in my case i need resolve the file store.js in src then i add this line: import store from '@/store.js';

@BetaLeev
Copy link

I have done that success with

 chainWebpack: config => {
        config.resolve.alias
            .set('api', path.resolve(__dirname, 'src/api'));
    },

@abdulladev1995
Copy link

While investigating this issue I have solved it like below and want to share others. Here are my vue.config.js file to support alias.

var path = require('path');

module.exports = {
    chainWebpack: config => {
        //this path is specific to my project
        config.resolve.alias.set('styles', path.resolve('src/assets/styles')); 
    },
};

And use it in Vue component with alias version (alias loading only worked with "~" but not with "@" sign):

<style lang="scss">
    @import "~styles/main";
    ...

</style>

@Archsx
Copy link

Archsx commented Jul 18, 2019

While investigating this issue I have solved it like below and want to share others. Here are my vue.config.js file to support alias.

var path = require('path');

module.exports = {
    chainWebpack: config => {
        //this path is specific to my project
        config.resolve.alias.set('styles', path.resolve('src/assets/styles')); 
    },
};

And use it in Vue component with alias version (alias loading only worked with "~" but not with "@" sign):

<style lang="scss">
    @import "~styles/main";
    ...

</style>

dude,It solved my problem.but can you tell me where did you find the solution?

@abdulladev1995
Copy link

dude,It solved my problem.but can you tell me where did you find the solution?

It is great to hear I have helped somebody. I have searched about this issue and tried multiple variants but any of helped me to specify directory based aliasing. So I want to give up after a lot of researching. But I did one last try and it worked!

@Dinuz
Copy link

Dinuz commented Dec 3, 2019

@abdulladev1995 you rock man! It solved the crappy ../../../ so glad:)))
Thank you

PS if you are using pycharm or webstorm don't forget to mark the assets directory as source

shingonu added a commit to tokamak-network/dashboard.tokamak.network that referenced this issue Jan 6, 2020
@FrankFang
Copy link
Contributor

FrankFang commented Jan 14, 2020

For WebStorm users: Dont forget to configure this. And then invalidate cache and restart
image

@Robula
Copy link

Robula commented Jan 29, 2020

Why is this issue closed? Vetur still can't properly infer custom paths.

@sean-hill
Copy link

I resolved my issue by adding in a jsconfig.json file at the root of my projects directory.

{
  "allowJs": true,
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src/**/*", "tests/**/*"],
  "exclude": ["node_modules"]
}

@ctsstc
Copy link

ctsstc commented May 20, 2020

Seems to not work with monorepos, but this may be more applicable and open: vuejs/vetur#762

@DavidRogersDev
Copy link

GitHub issues are for bug reports & feature requests only.
Next time please consider using forums for questions: https://forum.vuejs.org/c/chinese

Such aliases are already set.

.alias
.set('@', api.resolve('src'))

You can use configureWebpack or chainWebpack in vue.config.js to set your own aliases.

Ha! That's funny. Never ever got a response in those forums.

undergroundwires added a commit to undergroundwires/privacy.sexy that referenced this issue Apr 15, 2021
Alias would remove unnecessary repetitions and less relative paths make changes easier when moving around files. This commit cleans also up some relative paths ('../../../') by using the alias and orders imports. It updates both path alias in tsconfig and module alias in Vue CLI's bundler (vuejs/vue-cli#2398).
@andrew-d-moore
Copy link

andrew-d-moore commented Jan 15, 2022

This is the best way I've found to handle aliases, this doesn't just work with Vue it works with webpacks in general. I get that this isn't the place this is meant to go, but since this thread exists, may as well have a solid answer. This is essentially an automated way of creating the jsconfig.json file that @sean-hill mentions.

The files you create go in your root folder next to where your vue.config or webpacks.config file is. The file that is generated will show up there as well.

Requires: prettier npm i prettier --save

First you'll want to configure your Vue or Webpacks config file like below.

vue.config.js

  configureWebpack: {
    resolve: {
      alias: require('./aliases.config').webpack
    },
  },

Next you'll create a template file that is used when the aliases are generated.

jsconfig.template.js

// This is a template for a jsconfig.json file which will be
// generated when starting the dev server or a build.

module.exports = {
  baseUrl: '.',
  include: ['src/**/*', 'tests/**/*'],
  compilerOptions: {
    baseUrl: '.',
    target: 'esnext',
    module: 'es2015',
    // ...
    // `paths` will be automatically generated using aliases.config.js
    // ...
  },
}

Then you'll create the actual alias generator. Note that const aliases is where you'll want to put the names and paths to the folders you want aliased. I left Mine in for reference, you can leave unused aliases and it won't hurt, or remove them.

aliases.config.js

const path = require('path')
const fs = require('fs')
const prettier = require('prettier')

const aliases = {
  '@': '.',
  '@src': 'src',
  '@design': 'src/design',
  '@router': 'src/router',
  '@routes': 'src/router/routes',
  '@views': 'src/router/views',
  '@application': 'src/router/views/application',
  '@layouts': 'src/router/layouts',
  '@locales': 'src/locales',
  '@components': 'src/components',
  '@composables': 'src/composables',
  '@global-components': 'src/global-components',
  '@libs': 'src/libs',
  '@mixins': 'src/mixins',
  '@assets': 'src/assets',
  '@utils': 'src/utils',
  '@store': 'src/store',
}

module.exports = {
  webpack: {},
  jest: {},
  jsconfig: {},
}

for (const alias in aliases) {
  const aliasTo = aliases[alias]
  module.exports.webpack[alias] = resolveSrc(aliasTo)
  const aliasHasExtension = /\.\w+$/.test(aliasTo)
  module.exports.jest[`^${alias}$`] = aliasHasExtension
    ? `<rootDir>/${aliasTo}`
    : `<rootDir>/${aliasTo}/index.js`
  module.exports.jest[`^${alias}/(.*)$`] = `<rootDir>/${aliasTo}/$1`
  module.exports.jsconfig[alias + '/*'] = [aliasTo + '/*']
  module.exports.jsconfig[alias] = aliasTo.includes('/index.')
    ? [aliasTo]
    : [
      aliasTo + '/index.js',
      aliasTo + '/index.json',
      aliasTo + '/index.vue',
      aliasTo + '/index.scss',
      aliasTo + '/index.css',
    ]
}

const jsconfigTemplate = require('./jsconfig.template') || {}
const jsconfigPath = path.resolve(__dirname, 'jsconfig.json')

fs.writeFile(
  jsconfigPath,
  prettier.format(
    JSON.stringify({
      ...jsconfigTemplate,
      compilerOptions: {
        ...(jsconfigTemplate.compilerOptions || {}),
        paths: module.exports.jsconfig,
      },
    }),
    {
      ...require('./.prettierrc'),
      parser: 'json',
    }
  ),
  (error) => {
    if (error) {
      console.error(
        'Error while creating jsconfig.json from aliases.config.js.'
      )
      throw error
    }
  }
)

function resolveSrc(_path) {
  return path.resolve(__dirname, _path)
}

Finally a file like the below will be generated at run time, when you run npm run start or however you have configured your package to run.

jsconfig.json

{
  "baseUrl": ".",
  "include": ["src/**/*", "tests/**/*"],
  "compilerOptions": {
    "baseUrl": ".",
    "target": "esnext",
    "module": "es2015",
    "paths": {
      "@/*": ["./*"],
      "@": [
        "./index.js",
        "./index.json",
        "./index.vue",
        "./index.scss",
        "./index.css"
      ],
      "@src/*": ["src/*"],
      "@src": [
        "src/index.js",
        "src/index.json",
        "src/index.vue",
        "src/index.scss",
        "src/index.css"
      ],
      "@design/*": ["src/design/*"],
      "@design": [
        "src/design/index.js",
        "src/design/index.json",
        "src/design/index.vue",
        "src/design/index.scss",
        "src/design/index.css"
      ],
      "@router/*": ["src/router/*"],
      "@router": [
        "src/router/index.js",
        "src/router/index.json",
        "src/router/index.vue",
        "src/router/index.scss",
        "src/router/index.css"
      ],
      "@routes/*": ["src/router/routes/*"],
      "@routes": [
        "src/router/routes/index.js",
        "src/router/routes/index.json",
        "src/router/routes/index.vue",
        "src/router/routes/index.scss",
        "src/router/routes/index.css"
      ],
      "@views/*": ["src/router/views/*"],
      "@views": [
        "src/router/views/index.js",
        "src/router/views/index.json",
        "src/router/views/index.vue",
        "src/router/views/index.scss",
        "src/router/views/index.css"
      ],
      "@application/*": ["src/router/views/application/*"],
      "@application": [
        "src/router/views/application/index.js",
        "src/router/views/application/index.json",
        "src/router/views/application/index.vue",
        "src/router/views/application/index.scss",
        "src/router/views/application/index.css"
      ],
      "@layouts/*": ["src/router/layouts/*"],
      "@layouts": [
        "src/router/layouts/index.js",
        "src/router/layouts/index.json",
        "src/router/layouts/index.vue",
        "src/router/layouts/index.scss",
        "src/router/layouts/index.css"
      ],
      "@locales/*": ["src/locales/*"],
      "@locales": [
        "src/locales/index.js",
        "src/locales/index.json",
        "src/locales/index.vue",
        "src/locales/index.scss",
        "src/locales/index.css"
      ],
      "@components/*": ["src/components/*"],
      "@components": [
        "src/components/index.js",
        "src/components/index.json",
        "src/components/index.vue",
        "src/components/index.scss",
        "src/components/index.css"
      ],
      "@composables/*": ["src/composables/*"],
      "@composables": [
        "src/composables/index.js",
        "src/composables/index.json",
        "src/composables/index.vue",
        "src/composables/index.scss",
        "src/composables/index.css"
      ],
      "@global-components/*": ["src/global-components/*"],
      "@global-components": [
        "src/global-components/index.js",
        "src/global-components/index.json",
        "src/global-components/index.vue",
        "src/global-components/index.scss",
        "src/global-components/index.css"
      ],
      "@libs/*": ["src/libs/*"],
      "@libs": [
        "src/libs/index.js",
        "src/libs/index.json",
        "src/libs/index.vue",
        "src/libs/index.scss",
        "src/libs/index.css"
      ],
      "@mixins/*": ["src/mixins/*"],
      "@mixins": [
        "src/mixins/index.js",
        "src/mixins/index.json",
        "src/mixins/index.vue",
        "src/mixins/index.scss",
        "src/mixins/index.css"
      ],
      "@assets/*": ["src/assets/*"],
      "@assets": [
        "src/assets/index.js",
        "src/assets/index.json",
        "src/assets/index.vue",
        "src/assets/index.scss",
        "src/assets/index.css"
      ],
      "@utils/*": ["src/utils/*"],
      "@utils": [
        "src/utils/index.js",
        "src/utils/index.json",
        "src/utils/index.vue",
        "src/utils/index.scss",
        "src/utils/index.css"
      ],
      "@store/*": ["src/store/*"],
      "@store": [
        "src/store/index.js",
        "src/store/index.json",
        "src/store/index.vue",
        "src/store/index.scss",
        "src/store/index.css"
      ]
    }
  }
}

Once those are done you can use aliases all throughout your application. Example:

<template>
  <div>
    <img src='@assets/images/800x800.jpg/>
  </div>
</template>

<script>
  import SomeModule from '@components/some-module/SomeModule.vue
  import SomeModule from '@components/some-module/SomeModule

  export defaul {
  setup() {

  return {}
  },
  components: {
    SomeModule
  }
}
</script>

I put the import twice to show that you can import without putting the extension. Some people don't know this.

Hope this is helpful

@ivan006
Copy link

ivan006 commented Jan 31, 2023

For WebStorm users: Dont forget to configure this. image

and then invalidate cache and restart

LarrMarburger pushed a commit to LarrMarburger/privacy.sexy that referenced this issue Nov 16, 2023
Alias would remove unnecessary repetitions and less relative paths make changes easier when moving around files. This commit cleans also up some relative paths ('../../../') by using the alias and orders imports. It updates both path alias in tsconfig and module alias in Vue CLI's bundler (vuejs/vue-cli#2398).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests