【发布时间】:2023-01-30 18:32:27
【问题描述】:
在我的 vue3+vite 项目中,我使用的是官方的 fontawesome vue3 包(see use with vue)。
为了启用 tree-shaking,您需要使用 library.add 预先静态加载必要的图标(或可能全部)。参见例如以下App.vue
<script setup>
import { ref, computed } from "vue";
import { library } from "@fortawesome/fontawesome-svg-core";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { definition } from "@fortawesome/free-solid-svg-icons/faTruck";
library.add(definition);
const icon = ref("");
const showIcon = () => { icon.value = `fa-solid fa-truck`; };
</script>
<template>
<button @click="showIcon">Show Truck Icon</button>
<div v-if="icon">
<font-awesome-icon :icon="icon" />
</div>
</template>
在这里,我们静态加载卡车图标,当您单击按钮时,图标就会显示出来。
我试图做的是按需加载图标(在本例中,仅在单击按钮时),使用以下代码:
<script setup>
import { ref, computed } from "vue";
import { library } from "@fortawesome/fontawesome-svg-core";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
const modules = import.meta.glob(
"../node_modules/@fortawesome/free-solid-svg-icons/faTruck.js",
{ eager: false, import: "definition" }
);
const icon = ref("");
const showIcon = () => {
Object.values(modules)[0]().then((elem) => {
library.add(elem);
icon.value = `fa-solid fa-truck`;
});
};
</script>
<template>
<button @click="showIcon">Show Truck Icon</button>
<div v-if="icon">
<font-awesome-icon :icon="icon" />
</div>
</template>
但这在“开发”中不起作用(npm run dev):
- 它调用 http://localhost:5173/node_modules/@fortawesome/free-solid-svg-icons/faTruck.js
- 然后引发错误:
Uncaught (in promise) ReferenceError: exports is not defined
虽然它在构建包时工作正常(npm run build 然后例如使用 http-server 服务 dist 文件夹)
我怀疑这个问题与以下事实有关:在开发模式下,faTruck.js 模块是“按原样”使用的,而它是在构建阶段进行转换的。
有解决办法吗?
重现问题的完整步骤:
npm create vue@3 # accepts all defaults
cd vue-project
npm i @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/vue-fontawesome
# replace src/App.vue with the one indicated above
# run in dev with
npm run dev
# or build for prod and then expose using http-server
npm run build
npx http-server dist
【问题讨论】:
标签: vuejs3 font-awesome vite