如何使用webpack发出的字体文件?

时间:2017-07-28 14:39:15

标签: npm fonts webpack font-awesome webpack-2

摘要:

除了webpack之外,

bundle.js问题是font-awesome的字体文件。 bundle.js中未正确引用这些文件。

详细信息:

我有一个entry.js文件,输出到子目录(webpack)的子目录(dist)。 dist是独立的CDN可分发目录。由于站点生成器特定的原因(这个问题无关紧要),结构就是这样的。

(root folder for the site dev)
│   entry.js
│   webpack.config.js
│
└───dist
    │   index.html
    │
    └───webpack
            674f50d287a8c48dc19ba404d20fe713.eot
            912ec66d7572ff821749319396470bde.svg
            af7ae505a9eed503f8b8e6982036873e.woff2
            b06871f281fee6b241d60582ae9369b9.ttf
            bundle.js
            fee66e712a8a08eef5805a46892932ad.woff

index.html加载webpack/bundle.js并尝试使用Font Awesome:

<!DOCTYPE html>
<html lang="en">
    <head>
    </head>
    <body>
        hello world <i class="fa fa-shower"></i>
        <script src="webpack/bundle.js"></script>
    </body>
</html>

未正确引用字体文件,bundle.jswebpack中的网站根目录中查找它们,并在bundle.js中与bundle.js一起输出。换句话说,index.html:1 GET file:///D:/MegaSync/dev/webpack/testoffonts/dist/af7ae505a9eed503f8b8e6982036873e.woff2 net::ERR_FILE_NOT_FOUND index.html:1 GET file:///D:/MegaSync/dev/webpack/testoffonts/dist/fee66e712a8a08eef5805a46892932ad.woff net::ERR_FILE_NOT_FOUND index.html:1 GET file:///D:/MegaSync/dev/webpack/testoffonts/dist/b06871f281fee6b241d60582ae9369b9.ttf net::ERR_FILE_NOT_FOUND 不知道webpack.config.js指示它转到子目录。控制台上的输出(控制台输出):

bundle.js

如何提高/webpack/...的这种意识,以便它在与其本身相同的级别引用其输出生成的对等体(在我的情况下为entry.js)?

组件文件:

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

webpack.config.js

module.exports = { entry: "./entry.js", output: { path: __dirname + '/dist/webpack', // should use the path module filename: "bundle.js" }, module: { loaders: [ { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "file-loader" } ] } };

object sender

注意:在CSS文件中导入的字体不会出现此问题,因为现在我唯一的情况是将Font Awesome用作模块

1 个答案:

答案 0 :(得分:2)

该解决方案的所有功劳归于Jiggneshh Gohel及其detailed post on webpack GithHub

添加publicPath解决了问题:

output: {
        path: __dirname + '/dist/webpack', // should use the path module
        filename: "bundle.js",
        publicPath: "/webpack/",
    },

路径应该是捆绑包和其他发出的文件输出到的路径,相对于公开站点的根(http://example.com/)。