Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

杂文系列-webpack引入静态资源 #10

Open
aototo opened this issue Aug 28, 2017 · 0 comments
Open

杂文系列-webpack引入静态资源 #10

aototo opened this issue Aug 28, 2017 · 0 comments

Comments

@aototo
Copy link
Owner

aototo commented Aug 28, 2017

杂文系列-webpack静态资源-2017-8-28

基于webpack && html引入静态资源的几种方法

GitHub博客 https://github.com/asd0102433/blog 喜欢的start,长期更新


我们需要在页面插入图片:

index.html

<img src = 'assets/images/xxx.jpg' />

因为这个图片webpack并没有被加载进来,会得到404的结果。

通常的做法是在对应的js中require该资源

require('./assets/images/xxx.jpg');

这样就在内存中可以访问到内存中图片。(但是要注意文件加载的路径问题,最简单的就是按照构建的生产环境的资源路径)还要注意图片是否有hash值。

以下是js输出的图片资源路径

./images/acb790246029d8f127588eacd3005fbei1.jpg

比如最后生成的资源路径。页面也需要按照这样引入,显然是不可能的。

<img src = './images/acb790246029d8f127588eacd3005fbei1.jpg' />

当一个项目静态图片多的时候如何处理?比如一个不需要后端图片数据的前端活动页面?接下来有三种方法。

使用CopyWebpackPlugin

copy-webpack-plugin
把静态资源都拷贝到构建目录。使用方法也非常简单。

const CopyWebpackPlugin = require('copy-webpack-plugin');
Usage
new CopyWebpackPlugin([
	{ from: path , to: bundle_path }
])

这样就可以在页面中愉快的使用目录地址了(注意的是资源路径按照最终构建完成的目录)
如下是构建完毕后的目录

| dist
| ---- | images
| ---------- | xxx.jpg
| ---- | index.html

<img src='./images/xxxx.jpg' alt="">

CopyWebpackPlugin 能把全部静态资源全部拷贝过去,从而优化webpack在构建上面的速度,减少时间,是一个不错的优化方案,可以建议使用。

在 html文件中使用require

<img src='<%= require("./assets/images/xxx.jpg") %>'>

这种方法跟import是一样的,我们可以直接使用它,还可以配置alias,来简化这个path的名字

resolve: {
    alias: {
      imageBase: '../app/assets/images'
    },
 },

设置后页面中可以使用alias来代替路径问题

<img src='<%= require("imageBase/xxx.jpg") %>' >

同事css也可以使用,配合~

background: url('~imageBase/xxx.jpg')

此时~告诉webpack这是一个module,而不是相对路径。
webpack-contrib/css-loader#49
alias的使用同样也可以让构建的速度提升,直接锁定资源的地址,从而减少搜索的耗时。

使用html-loader

目前比较省力的方案

{
    test: /\.html$/,
    loader: 'html?attrs=img:src img:data-src'
}

它默认处理html中的<img src="image.png">为require("./image.png"),
同时还处理了hash文件名的问题。但是html-loader不支持下划线模板。会导致HtmlWebpackPlugin的变量模板失效。
具体问题:
jantimon/html-webpack-plugin#174
jantimon/html-webpack-plugin#223


以上的方法可以结合使用,比如2,3中使用的话,不但简化了图片的路径问题,还优化了构建速度,同时引入静态资源也非常的简单。

例子:

<img src='~imageBase/xxx.jpg' alt="">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant