Ways to use webpack aliases in Vue

Source: Internet
Author: User

At work, we often write this code:

importfrom‘../../components/m-header/m-header‘
@import "../../common/stylus/variable"@import "../../common/stylus/mixin"

That is, the common file needs to be introduced, but the file path of the public file is very far away, so the path of the example above will be very long.

The relative path cannot be modified because the file directory is conventional and cannot be easily changed. So what should we do?

As you know, JS in Vue can avoid a long list of path references by configuring Webpack aliases (alias), which is:

// targetimportfrom‘components/m-header/m-header‘//webpack.base.conf.jsalias:{    ‘@‘:resolve(‘src‘),    ‘common‘:resolve(‘src/common‘),    ‘components‘:resolve(‘src/components‘)}

However, if you use this method directly in CSS, you will get an error:

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

In fact, this method is not wrong, but webpack CSS processing is different from JS.

In JS, when the path is processed by Webpack, no path is automatically identified (/,./, ...). /) The first folder name is treated as a webpack alias. For example, if the first folder is named components , then Webpack will automatically search for aliases in alias, and if so, replace the path directly;

In CSS, the path is not processed by webpack 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"

The equivalent of adding ~ a common is a webpack alias instead of representing a folder name.

Proper use of WEBAPCK aliases can greatly shorten the time to ingest files.

Ways to use webpack aliases in Vue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.