vite vue3项目加载本地字体

Load local fonts in vite vue3 project

main.scss 中,我从 assets/styles/fonts 文件夹加载本地字体:

@font-face {
  font-family: 'Opensans-Bold';
  font-style: normal;
  src: local('Opensans-Bold'), url(./fonts/OpenSans-Bold.ttf) format('truetype');
}
@font-face {
  font-family: 'Opensans-Light';
  font-style: normal;
  src: local('Opensans-Light'), url(./fonts/OpenSans-Light.ttf) format('truetype');
}

然后在 vite.config 我加载 main.scss:

css: {
  preprocessorOptions: {
    scss: {
      additionalData: `@import "@/assets/styles/main.scss";`
    }
  }
},

但是 main.scss 中的所有 css 都被应用了,除了字体,我得到错误:

downloadable font: download failed (font-family: "Opensans-Bold" style:normal weight:400 stretch:100 src index:1): status=2152398850 source: http://localhost:3000/fonts/OpenSans-Bold.ttf

我是在正确的轨道上还是我需要一些其他方法(与 Vue-CLI 类似)?

原来是这样,解决方案是相对路径所以:

src: local('Opensans-Bold'), url(@/assets/styles/fonts/OpenSans-Bold.ttf) format('truetype');

并在 vite.config.js 中设置别名:

resolve: {
  alias: {
    '@': path.resolve(__dirname, 'src'),
  }
}