如何在CSS或是template中使用图片?在CSS中使用,先安装file-loader:
npm i -D file-loader
安装完成后,在package.json中看到的当前版本:
"file-loader": "^1.1.5"
接着在app.scss中加入下面的样式:
html, body{
height: 100%;
min-height: 100%;
background: url(./images/dog.jpg) center center no-repeat;
}
在src目录下已经新建了一个images的目录,并且有一个dog.jpg图片。
再到webpack.config.js中的新加一个rule来使用file-loader:
{
test: /\.jpg$/,
use: ['file-loader']
}
如果图片格式有很多,可以这么定义test:
test: /\.(png|jpg|gif)$/
重新build下,就可以看到下面的页面:
这样就把图片引入到了CSS中。
把图片引入到template中,在src目录下新建一个index.html:
<html lang=en>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<h1>this is the pug template header h1>
<h1>Pug - node template engineh1>
<div class=col id=container>
<p>Get on it!p>
<p>Pug is a terse and simple templating language with a strong focus on performance and powerful features.p>
div>
<img src="./images/dog.jpg"/>
show or not...
body>
把homepage模板也改成index.html(之前是my-index.pug):
new HtmlWebpackPlugin({
title: 'webpack',
excludeChunks:['anotherPage'],
hash: true,
template: './src/index.html'
})
如果像index.html中直接采用标准的html的格式直接引入图片,控制台会出现这样的error:
dog.jpg Failed to load resource: the server responded with a status of 404 (Not Found)
解决办法是采用EJS 关于EJS可以参考这里
%= require("./images/dog.jpg")%>/>
重新build后,就可以看图片被引入到页面当中了:
当执行prot命令时,可以看到在dist目录下生的图片:
可以看到生成的图片的名字是一串hash值,如果想让它保持原来的名字并也是生成images目录下,即最终的目录是这样:dist/images/dog.jpg,需要修改use:
use: ['file-loader?name=[name].[ext]&outputPath=images/']
dist 目录下生成的图片如dog.jpg,它实现上占用的空间会比较大,image-webapck-loader可以去优化这些事情,先去安装这个loader:
$ npm install image-webpack-loader --save-dev
安装完成后的当前版本是:
"image-webpack-loader": "^3.4.2",
然后更新rule:
{
test: /\.(png|jpg|gif)$/,
use: [
'file-loader?name=[name].[ext]&outputPath=images/',
'image-webpack-loader'
]
}
注意的是image-webpack-loader要放在file-loader的后面,顺序不能倒,先执行image-webpack-loader进行图片的优化后再通过file-loader save到指定的目录下。
在安装image-webapck-loader的过程出现了错误提示信息,虽然image-webpack-loader安装成功了:
➜ WebPack110 npm i -D image-webpack-loader
> cwebp-bin@3.2.0 postinstall /Users/Stan/Desktop/WebPack110/node_modules/cwebp-bin
> node lib/install.js
✔ cwebp pre-build test passed successfully
> gifsicle@3.0.4 postinstall /Users/Stan/Desktop/WebPack110/node_modules/gifsicle
> node lib/install.js
✔ gifsicle pre-build test passed successfully
> mozjpeg@4.1.1 postinstall /Users/Stan/Desktop/WebPack110/node_modules/mozjpeg
> node lib/install.js
⚠ The `/Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor/cjpeg` binary doesn't seem to work correctly
⚠ mozjpeg pre-build test failed
ℹ compiling from source
✖ Error: autoreconf -fiv && ./configure --disable-shared --prefix="/Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor" --bindir="/Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor" --libdir="/Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor" && make --jobs=8 && make install --jobs=8
Command failed: autoreconf -fiv
/bin/sh: autoreconf: command not found
at ChildProcess.exithandler (child_process.js:275:12)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at maybeClose (internal/child_process.js:925:16)
at Socket.stream.socket.on (internal/child_process.js:346:11)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at Pipe._handle.close [as _onclose] (net.js:554:12)
> optipng-bin@3.1.4 postinstall /Users/Stan/Desktop/WebPack110/node_modules/optipng-bin
> node lib/install.js
✔ optipng pre-build test passed successfully
> pngquant-bin@3.1.1 postinstall /Users/Stan/Desktop/WebPack110/node_modules/pngquant-bin
> node lib/install.js
✔ pngquant pre-build test passed successfully
+ image-webpack-loader@3.4.2
added 252 packages in 335.195s
当尝试去执行 npm run prot 命令时,就出错了:
➜ WebPack110 npm run prot
> webpack-stater@1.0.0 prot /Users/Stan/Desktop/WebPack110
> npm run clean && NODE_ENV=production webpack -p
> webpack-stater@1.0.0 clean /Users/Stan/Desktop/WebPack110
> rimraf ./dist/*
Hash: c730c3ef2023cb11a116
Version: webpack 3.8.1
Time: 2708ms
Asset Size Chunks Chunk Names
index.html 3.05 kB [emitted]
app.bundle.js 110 kB 0 [emitted] app
anotherPage.bundle.js 7.72 kB 1 [emitted] anotherPage
anotherPage.html 391 bytes [emitted]
[./src/anotherPage.js] ./src/anotherPage.js 59 bytes {1} [built]
[./src/app.js] ./src/app.js 570 bytes {0} [built]
[./src/app.scss] ./src/app.scss 993 bytes {0} [built] [failed] [1 error]
+ 15 hidden modules
ERROR in ./src/app.scss
Module build failed: ModuleBuildError: Module build failed: Error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.16.dylib
Referenced from: /Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor/cjpeg
Reason: image not found
at Promise.all.then.arr (/Users/Stan/Desktop/WebPack110/node_modules/execa/index.js:231:11)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
at runLoaders (/Users/Stan/Desktop/WebPack110/node_modules/webpack/lib/NormalModule.js:195:19)
at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js:364:11
at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js:230:18
at context.callback (/Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
at imagemin.buffer.then.catch.err (/Users/Stan/Desktop/WebPack110/node_modules/image-webpack-loader/index.js:92:9)
at
@ ./src/app.js 3:11-32
ERROR in ./src/app.scss
Module build failed: ModuleBuildError: Module build failed: Error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.16.dylib
Referenced from: /Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor/cjpeg
Reason: image not found
at Promise.all.then.arr (/Users/Stan/Desktop/WebPack110/node_modules/execa/index.js:231:11)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
at runLoaders (/Users/Stan/Desktop/WebPack110/node_modules/webpack/lib/NormalModule.js:195:19)
at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js:364:11
at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js:230:18
at context.callback (/Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
at imagemin.buffer.then.catch.err (/Users/Stan/Desktop/WebPack110/node_modules/image-webpack-loader/index.js:92:9)
at
@ ./src/app.scss
@ ./src/app.js
ERROR in Error: Child compilation failed:
Module build failed: Error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.16.dylib
Referenced from: /Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor/cjpeg
Reason: image not found
- index.js:231 Promise.all.then.arr
[WebPack110]/[execa]/index.js:231:11
- Error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.16.dylib
- Referenced from: /Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor/cjpeg
- Reason: image not found
从错误信息看像是缺少了libpng的library,当仔细看这里时,发现它有关于这个library的说明:关于libpng issues,按照它的说明,可以通过homebrew来完成安装,所以先安装homebrew:
sudo npm install -g brew
当前的brew版本是:
+ brew@0.0.8
added 1 package in 1.121s
继续安装libpng:
brew install libpng
发现又报错了:
pdating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
asciidoctor dps8m jabba mrboom simg2img
avimetaedit e2tools just ocaml-findlib terraform_landscape
bedtools elasticsearch@5.6 kaitai-struct-compiler ocaml-num ydcv
cling envconsul keystone pipenv
clingo go-jira kibana@5.6 raylib
csvkit heartbeat libxo restic
docker-ls htslib logstash@5.6 sceptre
==> Updated Formulae
abcm2ps geth lynis pyvim
abcmidi ghc macvim q
abyss gibo mailutils qca
aces_container git mairix qd
adplug git-annex mame qscintilla2
afl-fuzz git-cinnabar mapnik qt
alexjs git-cola mapserver qtfaststart
amazon-ecs-cli git-review mariadb rabbitmq
angband gitlab-runner mariadb@10.0 rakudo-star
angular-cli gjs mariadb@10.1 rancher-cli
ansible-cmdb gjstest mat rancid
antigen glib maxima ratfor
apache-geode glib-openssl mdds rbenv-bundler
apibuilder-cli glide media-info rdfind
app-engine-go-64 gmic mediaconch re2
app-engine-java gmime memcached re2c
apr-util gmsh menhir rebar@3
arangodb gmt mercurial redex
archivemount gmt@4 mesalib-glw redpen
aria2 gnu-time metricbeat regex-opt
armadillo gnu-units mg remake
artifactory gnupg mgba reminiscence
asciidoc gnuplot micro resty
aspcud gofabric8 micropython ringojs
aspectj goffice midnight-commander rocksdb
at-spi2-atk gomplate mighttpd2 rom-tools
at-spi2-core google-benchmark mikutter roswell
atlassian-cli gopass mingw-w64 rtags
aurora-cli gradle minimal-racket rust
aws-sdk-cpp gradle-completion minio sagittarius-scheme
aws-shell grafana miniupnpc sassc
awscli grails mitie sbcl
azure-cli grakn mkclean sbt
azure-cli@1 graphicsmagick mkdocs scalaenv
b2-tools gromacs mkvalidator scalapack
babl groovysdk mkvtoolnix scalariform
bacula-fd grpc mockserver scalastyle
bash-preexec gsmartcontrol modd scm-manager
bash-snippets gspell modules scons
bazel gtk+3 mongo-c-driver sdl2_mixer
bchunk gucharmap mongoose selenium-server-standalone
bibtexconv gutenberg monit sfk
binaryen gx mono-libgdiplus s-libev
bit gx-go mosh shairport-sync
bitcoin hadoop mpd shfmt
bitrise hana multimarkdown shibboleth-sp
blink1 harfbuzz mupdf shpotify
bluepill hashcat mupdf-tools sile
bmake hercules mvnvm silk
boost-mpi heroku mypy simple-obfs
bsponmpi highlight mysql-sandbox singular
buku hive nano sip
bwfmetaedit hivemind nanomsg sjk
bzt html-xml-utils nanopb-generator skinny
calcurse htmlcleaner nativefier smali
camlp4 htmldoc ncmpc smartmontools
camlp5 httest nco snakemake
casperjs huexpress ncview solr
ccm hugo neovim sonarqube
ceres-solver hyperscan netcdf source-to-image
certigo hypre nettle sourcekitten
chakra i2p nfdump sqlmap
charm-tools ibex nghttp2 src
checkstyle icoutils nickle ssdeep
chisel imagemagick nmh sslh
cimg imagemagick@6 node sslmate
citus imapfilter node-build sslyze
ckan immortal node@4 statik
clhep infer node@6 stoken
clojure influxdb nomad stormlib
closure-compiler inspircd notmuch streamlink
cmake iperf3 nss strongswan
cnats ipfs ntl stubby
cockatrice iron-functions nuget stunnel
cockroach ironcli nuttcp subnetcalc
cocot iso-codes ocaml suil
codemod ispc ocamlbuild suite-sparse
collectd itstool ocamlsdl sundials
commandbox jena octave supersonic
conan jenkins offlineimap svgo
conjure-up jenkins-lts omniorb swfmill
consul jfrog-cli-go ompl swi-prolog
consul-template jhipster opam swift-protobuf
convmv jmxtrans open-mpi swiftformat
convox jruby open-scene-graph swiftlint
coq json-fortran opencbm syncthing
corebird kerl opencoarrays taisei
couchdb keychain opencv task-spooler
cppad kibana openforti tectonic
crowdin knot opensaml telegraf
crystal-icr knot-resolver openssl telegram-cli
cython kobalt openssl@1.1 temporal_tables
davix kompose openvdb tenyr
dbus konoha opusfile terminal-notifier
dcos-cli kontena orc termius
debianutils kotlin ortp terraform
dependency-check kubectx osm2pgrouting terragrunt
dhall-json kubernetes-cli osquery texapp
diff-pdf kubernetes-helm osrm-backend texmath
diffoscope kvazaar overmind tfenv
django-completion lablgtk packer tgui
dmd lapack packetbeat thefuck
docfx latexila packetq tidy-html5
docker lbdb paket tinc
docker-completion ldc pandoc tintin
docker-compose lean-cli pandoc-citeproc tippecanoe
docker-compose-completion lgogdownloader pandoc-crossref traefik
doctl libass pango txt2tags
doitlive libassuan paperkey typescript
dscanner libatomic_ops parallel u-boot-tools
dssim libcddb passenger uftp
dub libcdio pazpar2 uncrustify
duck libcello pcb upscaledb
efl libconfig pcl urh
ejabberd libcouchbase pdfcrack userspace-rcu
elasticsearch libcue pdfpc vagrant-completion
erlang libdivecomputer pdftoedn vala
etcd libebur128 pdftoipe vapoursynth
etsh libetonyek pegtl varnish
exim libfabric percona-toolkit varnish@4
expat libfaketime pgpool-ii vault
exploitdb libfixbuf pgroonga vault-cli
eye-d3 libfreehand pgrouting vcdimager
faac libfreenect physfs vim
faas-cli libgosu pick vpcs
fabio libgsf pike vte3
fail2ban libhttpseverywhere pilosa vtk
fantom libical pioneers when
fd libmaxminddb planck wine
feedgnuplot libogg plantuml wireguard-tools
feh libopusenc plzip wpcli-completion
ffmpeg@2.8 libphonenumber pngquant wtf
fibjs libpq poco xctool
file-roller libpqxx poppler xmake
filebeat libre postgis xonsh
fio librealsense postgresql xrootd
firebase-cli libressl postgresql@9.4 xtensor
fish libsass postgresql@9.5 xxhash
flatbuffers libtensorflow postgresql@9.6 yaf
flawfinder libtiff pqiv yara
flow libtorrent-rasterbar pre-commit yarn
fluent-bit libtrace prest yash
fn libuv presto yaze-ag
folly libvirt primesieve yle-dl
fonttools libwebsockets proguard you-get
fossil libwpg prometheus youtube-dl
freetds libwps protobuf z80dasm
frugal libxml2 protobuf-c zabbix
fswatch libxslt protobuf-swift zanata-client
fwup lighttpd psftools zbackup
gauge link-grammar pumba zenity
gdcm linkerd pure-ftpd zimg
gdnsd little-cms2 purescript zint
geckodriver lldpd pushpin zmqpp
gegl logstash py2cairo zurl
geoipupdate logtalk py3cairo
geoserver lwtools pyqt
getdns lxc python-markdown
==> Renamed Formulae
findbugs -> spotbugs newsbeuter -> newsboat
==> Deleted Formulae
clasp gringo
Error: Xcode alone is not sufficient on Sierra.
Install the Command Line Tools:
xcode-select --install
从最后一行可以看到说我现在用的Xcode有问题,它推荐去执行xcode-select –install这个命令,难道要重新安装Xcode,然后先google下有没有遇到过类似的问题,有个小伙伴也遇到类似的问题:install some missing command line tools in Xcode ,上面这个命令是要去安装Command Line Tools,所以就先去安装:
xcode-select --install
执行之后就只有一句提示:
xcode-select: note: install requested for command line developer tools
然后再去执行brew install libpng,就可以看到下面的提示信息:
安装成功了,这个时候再去执行npm run prot,再没有错误信息了,然后这个时候去看下dist目录下的dog.png,看下它的大小是31KB:
再看下src目录下的dog.png,它的原始大小是55KB,被压缩了将一半: