在使用 vue-cli webpack 创建的 Vue 应用程序中使用 font-awesome

Use font-awesome in a Vue app created with vue-cli webpack

我正在尝试在使用 webpack-simple 模板的 vue-cli 创建的简单 Vue 应用程序中使用 font-awesome,但这很棘手。

我使用 npm install font-awesome --save 安装了 font-awesome 并将其导入到我的条目 js (main.js)

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router';
import Home from "./components/Home.vue"

Vue.use(VueRouter);

import 'font-awesome/css/font-awesome.css';

const routes = [
    { path: '/', component: Home }
];

const router = new VueRouter({
    routes,
    mode: 'history'
});

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

这是我当前的 webpack.config.js 文件:

var path = require('path')
var webpack = require('webpack')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/dist/',
    filename: 'build.js'
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // Since sass-loader (weirdly) has SCSS as its default parse mode, we map
            // the "scss" and "sass" values for the lang attribute to the right configs here.
            // other preprocessors should work out of the box, no loader config like this nessessary.
            'scss': 'vue-style-loader!css-loader!sass-loader',
            'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
          }
          // other vue-loader options go here
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/, 
        loader: 'file-loader',
        options: {
          name: '[name].[ext]?[hash]'
        }
      },
      {
        test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url?limit=10000&mimetype=application/font-woff"
      }, {
        test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url?limit=10000&mimetype=application/font-woff"
      }, {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url?limit=10000&mimetype=application/octet-stream"
      }, {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        loader: "file"
      }, {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        loader: "url?limit=10000&mimetype=image/svg+xml"
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.common.js'
    }
  },
  devServer: {
    historyApiFallback: true,
    noInfo: true
  },
  performance: {
    hints: false
  },
  devtool: '#eval-source-map'
}

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

我已经尝试将字体加载器更改为以下内容:

{
    test: /\.(png|jpe|jpg|gif|woff|woff2|eot|ttf|svg)(\?.*$|$)/,
    loader: 'file-loader',
    options: {
      name: '[name].[ext]?[hash]'
    }
}

但是两种配置都会抛出相同的错误:

ERROR in ./~/font-awesome/css/font-awesome.css
Module parse failed: /home/james/projects/app/node_modules/font-awesome/css/font-awesome.css Unexpected character '@' (7:0)
You may need an appropriate loader to handle this file type.
| /* FONT PATH
|  * -------------------------- */
| @font-face {
|   font-family: 'FontAwesome';
|   src: url('../fonts/fontawesome-webfont.eot?v=4.7.0');
 @ ./src/main.js 11:0-43
 @ multi main

经过一些 google 之后,我找到了一些链接(例如 here, here and here),但是它们中的任何一个都对我有用,错误总是一样的。

推荐的处理超赞字体文件的加载程序是什么?我认为问题出在加载程序中,因为所有正则表达式对我来说都很好。

有关信息,以下是 package.json 中的版本:

"dependencies": {
    "bulma": "^0.3.0",
    "font-awesome": "^4.7.0",
    "vue": "^2.1.0",
    "vue-resource": "^1.0.3",
    "vue-router": "^2.1.1"
  },
  "devDependencies": {
    "babel-core": "^6.0.0",
    "babel-loader": "^6.0.0",
    "babel-preset-es2015": "^6.0.0",
    "cross-env": "^3.0.0",
    "css-loader": "^0.25.0",
    "file-loader": "^0.9.0",
    "style-loader": "^0.13.1",
    "vue-loader": "^10.0.0",
    "vue-template-compiler": "^2.1.0",
    "webpack": "^2.1.0-beta.25",
    "url-loader": "^0.5.5",
    "webpack-dev-server": "^2.1.0-beta.9"
  }

您似乎需要在 webpack 配置中包含 .css 的加载程序:

  {
    test: /\.css$/,
    loader: 'css-loader'
  },

随着 FontAwesome-5 的发布,FontAwesome 团队为 vue 和其他库做了一些独家的事情:

有点过时的解决方案但仍然有效,请检查下面的更新解决方案:

  • 检查 fontawesome 高级选项 here
  • 对于 npm 包和文档检查 here

无论如何,这是我首先整合它所做的 安装了这些软件包:

npm i --save @fortawesome/fontawesome
npm i --save @fortawesome/vue-fontawesome
npm i --save @fortawesome/fontawesome-free-solid

创建一个名为 fa.config.js 的文件并包含以下代码:

import Vue from 'vue';
import fontawesome from '@fortawesome/fontawesome';
import FontAwesomeIcon from '@fortawesome/vue-fontawesome';
import {
  faSpinner,
  faAngleLeft,
  faAngleRight,
} from '@fortawesome/fontawesome-free-solid';

fontawesome.library.add(
  faSpinner,
  faAngleLeft,
  faAngleRight,
);

Vue.component('font-awesome-icon', FontAwesomeIcon); // registered globally

并将其导入 main.js

import './path/to/fa.config';

在我的组件中,我是这样使用它的:

<template>
  <div>
    <font-awesome-icon icon="angle-left"></font-awesome-icon> Hey! FA Works
  </div>
</template>

现在你们可能已经明白我上面这样做的好处是什么了?

Using an explicit icon offers the advantage of only bundling the icons that you use in your final bundled file. This allows us to subset Font Awesome's thousands of icons to just the small number that are normally used.

希望这对您有所帮助!


更新 - 2018 年 6 月 22 日,星期五
上面的解决方案仍然有效,但现在以不同的方式完成,首先安装这些包:

npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/free-regular-svg-icons // if "regular" icon package needed
npm i --save @fortawesome/vue-fontawesome

然后创建一个名为 fa.config.js 的文件并包含以下代码:

import Vue from 'vue';
import { library } from '@fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'

import { faUser, faBuilding } from '@fortawesome/free-solid-svg-icons'
import { faUserCircle, faCheckCircle } from '@fortawesome/free-regular-svg-icons'

library.add(
  faUser,
  faBuilding,
  faUserCircle,
  faCheckCircle,
);

Vue.component('font-awesome-icon', FontAwesomeIcon); // registered globally

假设您喜欢使用 regularsolid 两种类型的 faUser 图标,然后进行以下更改:

import { faUser as fasUser, faBuilding } from '@fortawesome/free-solid-svg-icons'
import { faUser as farUser, faCheckCircle } from '@fortawesome/free-regular-svg-icons'

library.add(
  fasUser,
  farUser,
  faBuilding,
  faCheckCircle,
);

并将其导入main.js

import './path/to/fa.config';

在我的组件中,我是这样使用它的:

<template>
  <div>
    <font-awesome-icon icon="user"></font-awesome-icon>

    // If you like to use Font Awesome Regular, then:
    <font-awesome-icon :icon="['far', 'user']"></font-awesome-icon>
    <font-awesome-icon :icon="['far', 'check-circle']"></font-awesome-icon>

  </div>
</template>

我使用简单的解决方案webpack:

webpack.config.js:

const path = require('path')

module.exports = {
    resolve: {
        alias: {
            '@': path.resolve('resources/js')
        }
    }
}

webpack.mix.js

mix.js('resources/js/app.js', 'public/js').vue()
    .sass('resources/sass/app.scss', 'public/css')
    .webpackConfig(require('./webpack.config'))

if (mix.inProduction()) {
    mix.version()
}

在app.scss

中使用sass
@import '~@fortawesome/fontawesome-free/scss/brands.scss';
@import '~@fortawesome/fontawesome-free/scss/fontawesome.scss';
@import '~@fortawesome/fontawesome-free/scss/regular.scss';
@import '~@fortawesome/fontawesome-free/scss/solid.scss';

安装所有依赖 我在 package.json:

中使用
"@fortawesome/fontawesome-free": "^5.15.4",
"@fortawesome/free-brands-svg-icons": "^5.15.4",
"@fortawesome/free-regular-svg-icons": "^5.15.4",
"@fortawesome/free-solid-svg-icons": "^5.15.4",

不要破坏你的 main 并调用它

<i class="fa fa-icon> </i>
<i class="fas fa-icon> </i> // for solid
<i class="far fa-icon> </i> // for Regular

想象一下品牌怎么样!

用于 fa 和 fab 图标

使用 npm :

npm install --save @fortawesome/fontawesome-free-brands
npm install --save @fortawesome/fontawesome-free-solid
npm install --save @fortawesome/fontawesome

在 Main.js 中:

// font awesome 5 
import fontawesome from "@fortawesome/fontawesome";
import solid from "@fortawesome/fontawesome-free-solid";
import brands from "@fortawesome/fontawesome-free-brands";

fontawesome.library.add( brands , solid);

并像通常在网站开发中那样调用图标

在 home.vue 中:

<a href="#!" class="text-white me-4">
    <i class="fab fa-facebook-f" />
 </a>