如何解決webpack打包後直接存取頁面圖片路徑錯誤

來源:互聯網
上載者:User
這篇文章主要給大家介紹了在webpack打包後直接存取頁面圖片路徑錯誤的解決方案,文中介紹的非常詳細,對遇到這個問題的朋友們具有一定的參考學習價值,需要的朋友們下面來一起看看吧。

前言

本文說的這種圖片路徑錯誤是這樣的,運行webpack-dev-server,一切正常,沒有錯誤。當webpack之後,直接開啟index頁面,報錯,圖片找不到,找不到的原因是路徑錯誤。

先看我的項目代碼

webpack.config.js

var Webpack = require("webpack");var path = require("path");module.exports = { entry: './js/entry.js', output: { path: path.join(__dirname, '/build'), filename: 'bundle.js', publicPath: "/src/" }, module: { loaders: [{  test: /\.css$/,  loader: 'style-loader!css-loader'  }, {  test: /\.(png|jpg)$/,  loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]'  },   {  test: require.resolve('zepto'),  loader: 'exports-loader?window.Zepto!script-loader'  } ] }, watch: true, devtool: "cheap-module-eval-source-map"}

這裡設定了publicPath,用法點擊這裡

index.html中引用路徑如下:

<script type="text/javascript" src="src/bundle.js" ></script>

當運行webapck-dev-server時,http://localhost:8080/顯示正常。

緊接著,要打包,目的是脫離命令能直接存取頁面。

操作如下:

  1.執行webpack

  2.將build中的檔案全部拷貝到src中

  3.查看頁面

因為圖片路徑錯誤,所以找不到圖片。

我通過單獨給處理圖片的loader設定publicPath解決了這個問題,如下:

   {  test: /\.(png|jpg)$/,  loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]',  options:{   publicPath:'/'  }  }

然後測試,webapck-dev-server成功,wepback成功,開啟頁面訪問,成功。

路徑是這個樣子的。

以上就是本文的全部內容,希望對大家的學習有所協助,更多相關內容請關注topic.alibabacloud.com!

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.