使用webpack时打包后-解析的scss文件中的字体路径出错

  • 打包前文件路径和scss文件
- fonts
    - element-icons.woff
    - element-icons.ttf
- scss
    - icon.scss
$--font-path: "./fonts" !default;
$--font-display: "auto" !default;
$--icon-width-base: 20px !default;
$--icon-height-base: 20px !default;

@font-face {
  font-family: "element-icons";
  /* chrome, firefox */ /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/
  src: url("#{$--font-path}/element-icons.woff") format("woff"),
    url("#{$--font-path}/element-icons.ttf") format("truetype");
  font-weight: normal;
  font-display: $--font-display;
  font-style: normal;
}
  • 打包后文件路径和scss文件
- fonts
    - element-icons.f1a45d74.ttf
    - element-icons.ff18efd1.woff
- snineUI.css
@font-face {
  font-family: element-icons;
  /*此处url 应为 url(./fonts/element-icons.ff18efd1.woff) 但是打包后不是的*/
  src: url(/fonts/element-icons.ff18efd1.woff) format("woff"),
    url(/fonts/element-icons.f1a45d74.ttf) format("truetype");
  font-weight: 400;
  font-display: "auto";
  font-style: normal;
}
  • vue.config.js 配置
// 隐去的是 试过但是无效的
const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
  transpileDependencies: true,
  pages: {
    index: {
      // 修改入口
      entry: "examples/main.js",
      template: "public/index.html",
      filename: "index.html",
    },
  },
  // rules: [
  //   {
  //       test: /\.scss?$/,
  //       loader: "sass-loader",
  //       use: extractTextPlugin.extract({
  //         publicPath:'.',
  //       })
  //   },
  // ],
  chainWebpack: (config) => {
    config.module
      .rule("js")
      .include.add("/packages")
      .end()
      .use("babel")
      .loader("babel-loader")
      .tap((options) => {
        return options;
      });
    // config.module
    //   .rule("css")
    //   .test(/\.css$/)
    //   .use("style-loader")
    //   .loader("style-loader")
    //   .end()
    //   .use("css-loader")
    //   .loader("css-loader");
    // config.module
    //   .rule("svg")
    //   .test(/\.(svg|otf|ttf|woff2?|eot|gif|png|jpe?g)(\?\S*)?$/)
    //   .use("url-loader")
    //   .loader("url-loader")
    //   .options({
    //     limit: 10000,
    //     name: path.posix.join("static", "[name].[hash:7].[ext]"),
    //   });
  },
});

添加配置 publicPath: './' 就可以了

const { defineConfig } = require("@vue/cli-service");
module.exports = defineConfig({
  // 添加这个
  publicPath: './',
  // ...其他代码
});
 

【相关推荐】



  • 这篇博客: webpack配置大全中的 5.3 打包scss文件 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:

    ① 运行 npm i style-loader sass-loader node-sass -D命令安装处理css文件的loader

    ② 配置webpack.config.js的module中的rules数组

    module.exports = {
            ......
            module : {
                rules:[
                    {   test:/\.scss$/, use:['style-loader','css-loader','sass-loader']  }
                ]
            }
        }
    

    注:node-sass一般很难装上


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^