SoFunction
Updated on 2025-04-04

Detailed explanation of the method example of using webpack alias in Vue

At work, we often write this kind of code:

import MHeader from '../../components/m-header/m-header'
@import "../../common/stylus/variable"
@import "../../common/stylus/mixin"

That is, if a public file needs to be introduced, but the current file in the file path of the public file is very far away, then the path in the above example will be formed.

Because the file directory is conventional, it cannot be changed easily and the relative path cannot be modified. So what should I do?

As we all know, js in Vue can avoid a long list of path references by configuring webpack alias (alias), i.e.:

// target
import MHeader from 'components/m-header/m-header'
//
alias: {
  '@': resolve('src'),
  'common': resolve('src/common'),
  'components': resolve('src/components')
}

However, if you use this method directly in css, an error will be reported:

@import "common/stylus/variable"  // error
@import "common/stylus/mixin"    // error

In fact, this method is not wrong, but webpack handles css differently from js.

In js, when webpack processes paths, the first folder name without path identifier (/, ./, ../) is automatically treated as a webpack alias. For example, if the first folder is called components, webpack will automatically search for the corresponding alias in alias. If there is, it will directly replace the path; if there is no, an error will be reported.

In css, webpack does not process the path under normal circumstances. If you want webpack to process the path, you can identify it before the path, as follows:

@import "~common/stylus/variable"
@import "~common/stylus/mixin"

It is equivalent to adding ~ to indicate that common is a webpack alias instead of a folder name.

Correct use of the webapck alias can greatly shorten the time to introduce files.

Summarize

The above is a detailed explanation of the method of using webpack alias in Vue introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!