天天看點

Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題

如何在CSS或是template中使用圖檔?在CSS中使用,先安裝file-loader:

安裝完成後,在package.json中看到的目前版本:

接着在app.scss中加入下面的樣式:

html, body{
    height: %;
    min-height: %;
    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:

重新build下,就可以看到下面的頁面:

Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題

這樣就把圖檔引入到了CSS中。

把圖檔引入到template中,在src目錄下建立一個index.html:

<!DOCTYPE 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>Document</title>
    </head>

<body>
    <h1>this is the pug template header </h1>
    <h1>Pug - node template engine</h1>
    <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  (Not Found)
           

解決辦法是采用EJS 關于EJS可以參考這裡

<img src=<%= require("./images/dog.jpg")%>/>
           

重新build後,就可以看圖檔被引入到頁面當中了:

Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題

當執行prot指令時,可以看到在dist目錄下生的圖檔:

Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題

可以看到生成的圖檔的名字是一串hash值,如果想讓它保持原來的名字并也是生成images目錄下,即最終的目錄是這樣:dist/images/dog.jpg,需要修改use:

use: ['file-loader?name=[name].[ext]&outputPath=images/']
           
Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題

dist 目錄下生成的圖檔如dog.jpg,它實作上占用的空間會比較大,image-webapck-loader可以去優化這些事情,先去安裝這個loader:

安裝完成後的目前版本是:

"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

> [email protected] postinstall /Users/Stan/Desktop/WebPack110/node_modules/cwebp-bin
> node lib/install.js

  ✔ cwebp pre-build test passed successfully

> [email protected] postinstall /Users/Stan/Desktop/WebPack110/node_modules/gifsicle
> node lib/install.js

  ✔ gifsicle pre-build test passed successfully

> [email protected] 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= && make install --jobs=
Command failed: autoreconf -fiv
/bin/sh: autoreconf: command not found

    at ChildProcess.exithandler (child_process.js::)
    at emitTwo (events.js::)
    at ChildProcess.emit (events.js::)
    at maybeClose (internal/child_process.js::)
    at Socket.stream.socket.on (internal/child_process.js::)
    at emitOne (events.js::)
    at Socket.emit (events.js::)
    at Pipe._handle.close [as _onclose] (net.js::)

> [email protected] postinstall /Users/Stan/Desktop/WebPack110/node_modules/optipng-bin
> node lib/install.js

  ✔ optipng pre-build test passed successfully

> [email protected] postinstall /Users/Stan/Desktop/WebPack110/node_modules/pngquant-bin
> node lib/install.js

  ✔ pngquant pre-build test passed successfully
+ [email protected]
added  packages in s
           

當嘗試去執行 npm run prot 指令時,就出錯了:

➜  WebPack110 npm run prot

> [email protected] prot /Users/Stan/Desktop/WebPack110
> npm run clean && NODE_ENV=production webpack -p


> [email protected] clean /Users/Stan/Desktop/WebPack110
> rimraf ./dist/*

Hash: c730c3ef2023cb11a116
Version: webpack 
Time: ms
                Asset       Size  Chunks             Chunk Names
           index.html     kB          [emitted]
        app.bundle.js      kB         [emitted]  app
anotherPage.bundle.js     kB         [emitted]  anotherPage
     anotherPage.html   bytes          [emitted]
[./src/anotherPage.js] ./src/anotherPage.js  bytes {} [built]
[./src/app.js] ./src/app.js  bytes {} [built]
[./src/app.scss] ./src/app.scss  bytes {} [built] [failed] [ error]
    +  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.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::)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js::)
    at runLoaders (/Users/Stan/Desktop/WebPack110/node_modules/webpack/lib/NormalModule.js::)
    at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js::
    at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js::
    at context.callback (/Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js::)
    at imagemin.buffer.then.catch.err (/Users/Stan/Desktop/WebPack110/node_modules/image-webpack-loader/index.js::)
    at <anonymous>
 @ ./src/app.js :-

ERROR in ./src/app.scss
Module build failed: ModuleBuildError: Module build failed: Error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.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::)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js::)
    at runLoaders (/Users/Stan/Desktop/WebPack110/node_modules/webpack/lib/NormalModule.js::)
    at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js::
    at /Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js::
    at context.callback (/Users/Stan/Desktop/WebPack110/node_modules/loader-runner/lib/LoaderRunner.js::)
    at imagemin.buffer.then.catch.err (/Users/Stan/Desktop/WebPack110/node_modules/image-webpack-loader/index.js::)
    at <anonymous>
 @ ./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.dylib
    Referenced from: /Users/Stan/Desktop/WebPack110/node_modules/mozjpeg/vendor/cjpeg
    Reason: image not found

  - index.js: Promise.all.then.arr
    [WebPack110]/[execa]/index.js::



  - Error: dyld: Library not loaded: /usr/local/opt/libpng/lib/libpng16.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..
added  package in s
           

繼續安裝libpng:

brew install libpng
           

發現又報錯了:

pdating Homebrew...
==> Auto-updated Homebrew!
Updated  tap (homebrew/core).
==> New Formulae
asciidoctor             dps8m                   jabba                   mrboom                  simg2img
avimetaedit             e2tools                 just                    ocaml-findlib           terraform_landscape
bedtools                [email protected]       kaitai-struct-compiler  ocaml-num               ydcv
cling                   envconsul               keystone                pipenv
clingo                  go-jira                 [email protected]              raylib
csvkit                  heartbeat               libxo                   restic
docker-ls               htslib                  [email protected]            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                 [email protected]                  rakudo-star
angular-cli                   gjs                           [email protected]                  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-              gmic                          mediaconch                    re2
app-engine-java               gmime                         memcached                     re2c
apr-util                      gmsh                          menhir                        [email protected]
arangodb                      gmt                           mercurial                     redex
archivemount                  [email protected]                         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@                   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+                         mongo-c-driver                sdl2_mixer
bchunk                        gucharmap                     mongoose                      selenium-server-standalone
bibtexconv                    gutenberg                     monit                         sfk
binaryen                      gx                            mono-libgdiplus               shadowsocks-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                          [email protected]                 node                          sslmate
citus                         imapfilter                    node-build                    sslyze
ckan                          immortal                      [email protected]                        statik
clhep                         infer                         [email protected]                        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
co                         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                        openfortivpn                  tectonic
crowdin                       knot                          opensaml                      telegraf
crystal-icr                   knot-resolver                 openssl                       telegram-cli
cython                        kobalt                        [email protected]                   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               [email protected]
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
[email protected]                    libphonenumber                pngquant                      wtf
fibjs                         libpq                         poco                          xctool
file-roller                   libpqxx                       poppler                       xmake
filebeat                      libre                         postgis                       xonsh
fio                           librealsense                  postgresql                    xrootd
firebase-cli                  libressl                      [email protected]                xtensor
fish                          libsass                       [email protected]                xxhash
flatbuffers                   libtensorflow                 [email protected]                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,是以就先去安裝:

執行之後就隻有一句提示:

然後再去執行brew install libpng,就可以看到下面的提示資訊:

Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題

安裝成功了,這個時候再去執行npm run prot,再沒有錯誤資訊了,然後這個時候去看下dist目錄下的dog.png,看下它的大小是31KB:

Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題

再看下src目錄下的dog.png,它的原始大小是55KB,被壓縮了将一半:

Webpack 3.x 在CSS和Template中使用file-loader及解決image-webpack-loader 優化圖檔問題