url 和 css 模块中的波浪号不起作用

Tilde in url with css modules does not work

您有一些可行的示例配置吗?

webpack 设置:

{
  test: /\.scss$/,
  use: ['style-loader', {
    loader: 'css-loader',
    options: {
      modules: true,
      localIdentName: '[local]--[hash:base64:5]',
    },
  }, 'sass-loader'],
},

用法:

background: url('~assets/arrow-white.svg') center no-repeat;

输出:

Module not found: Error: Can't resolve './assets/arrow-white.svg'

我可以省略 ~ 或使用 ~/../assets 并且它有效,但我只想使用它 ~.

我只是复制你的评论,以便你可以关闭这个问题

the problem is that css-modules mode changes path resolution and doesn't respect webpack module resolution

使用这个包https://github.com/P0lip/url-tilde-loader

// In your webpack config
{
  test: /\.s?css$/,
  use: [
    'style-loader',
    {
      loader: "css-loader",
      options: {
        modules: true,
      },
    },
    {
      loader: 'url-tilde-loader'
      options: {
        replacement: '~/../', // string to replace with
        traverse: false, // use manual traversing
      },
    },
  ]
}