The cause of

When packaging is processed with Webpack, a directory can be configured with an alias, and resources can be referenced in the code using a path relative to the alias.

In Vue projects, we typically use vue-Webpack scaffolding to generate the project template, and then configure @to alias the/SRC directory that places the resources and source code in the project root directory;

. .resolve: {... .alias: {
    The '@': resolve('src')}}Copy the code

This way we can refer to/SRC /utils/xxx.js in a js file with import tool from ‘@/utils/ XXX ‘and Webpack will recognize and package it correctly.

However, in CSS files such as less, sass, or stylus, using @import “@/style/theme” syntax to reference the directory relative to @ does result in an error, “‘@’ directory not found”, indicating that WebPack does not correctly identify the relative path of the resource.

Analysis of the

The reason is that CSS files will be processed by CSS-loader, and the string after CSS-@ import will be treated as an absolute path by CSS-loader. Because we have not added the ALIAS of CSS-Loader, the @ directory will not be reported.

To solve

There are two solutions to CSS import using alias relative paths in Webpack;

First, add ailAS path for CSS-loader directly, but in vue-webpack to the template, add configuration for this plug-in is troublesome redundancy;

Add a ~ symbol (@import “~@/style/theme”) to the front of the string referencing the path. Webpack resolves paths prefixed with the ~ symbol as dependent modules so that the @ alias configuration takes effect.

conclusion

~ module parsing is something webpack does, not CSS-Loader does.

All kinds of non-JS direct reference (import require) static resources, dependent on the relative path loading problem, can use ~ syntax perfect solution;

For example, in the CSS Module: @import “~@/style/theme”

CSS properties: BACKGROUND: URL (“~@/assets/xxx.jpg”)

The resources

  • Vue-webpack resource path handling
  • Using url(path) with resolve.alias
  • CSS Loader Usage Url

From: a wiki. ZTHXXX. Me/wiki / % % E6 8 a…