在使用webpack-dev-server開發的時候,訪問資源路徑出了不少問題,挖了不少坑,找了一些資料,本身跟着敲了一下,現記錄一下。
參考博客:
webpack 配置 publicPath的理解
這篇博客寫的output裏的publicPath,寫的很詳細很清楚了css
webpack新手入門的教程裏,在寫package.json
文件時,一般設置爲:html
"script":{
"build":"webpack --config webpack.config.js",
"dev":"webpack-dev-server --config webpack.config.ks"
}
複製代碼
這是由於在開發過程當中,一般使用webpack-dev-server
,由於具備熱更新功能,而在生產時,則是使用webpack
打包成js文件。
publicPath
解釋最多的是說訪問靜態資源時的路徑,當咱們把資源放到CDN上的時候,把 publicPath
設爲CDN的值就好了,這種使用方法適用於生產環境,而使用webpack-dev-server
開發時,publicPath
指的是使用webpack-dev-server
打包後生成的資源存放的位置。
默認狀況下,webpack-dev-server
打包的資源放在根目錄下,即localhost:8000/下,只是它打包的資料是存放在內存中,在項目目錄裏看不到,打開瀏覽器的開發者模式,在source裏能夠看到。
用webpack敲博客案例試一下,分爲兩種狀況,手動建立html文件和使用html-webpack-plugin插件建立html兩種狀況。webpack
webpack-demo
|-src
|-index.js --入口文件
|-img
|-big.png
|-index.html --根頁面
|-webpack.config.js
|-package.json
複製代碼
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webpack Tut</title>
</head>
<body>
</body>
</html>
複製代碼
// src/index.js
import img from './img/big.png';
var imgElement = document.createElement('img');
imgElement.src = img;
document.body.appendChild(imgElement);
複製代碼
// webpack.config.js
const path = require('path');
module.exports = {
entry: path.join(__dirname, 'src/index.js'),
output: {
path: path.join(__dirname, 'dist'),
filename:'bundle.js'
},
module: {
rules:[
{
test: /\.(png|jpg)$/,
loader: 'url-loader',
options: {
limit: 3000,
name: '[name].[hash:8].[ext]'
}
}
]
}
}
複製代碼
首先使用webpack-dev-server
打包,按照前面說的,默認狀況下打包路徑在根目錄下,因此在index.html中使用'scr="./bundle.js"'來引入js文件,npm run dev
後打開localhost:8000能夠看到圖片已經加載出來。webpack-dev-server
默認尋找運行該命令的路徑下的index.html文件,此時項目根目錄有該文件因此就開始解析。 web
src="./dist/bundle.js"
,再從新打包查看,發現js文件已經加載成功,可是圖片路徑不對,圖片是相對於根目錄的,可是圖片資源如今存在dist文件夾下。
puhcliPath:'/dist/'
,就能夠訪問到資源。
刪除根目錄下的index.html,而後安裝html-webpack-plugin自動建立html.npm
// webpack.config.js
const path = require('path');
// 引入webpack 和 html-webpack-plugin插件
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.join(__dirname, 'src/index.js'),
output: {
path: path.join(__dirname, 'dist'),
filename:'bundle.js',
publicPath: '/dist/'
},
module: {
rules:[
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|jpg)$/,
loader: 'url-loader',
options: {
limit: 10000,
name: '[name].[hash:8].[ext]'
}
}
]
},
plugins: [
new htmlWebpackPlugin() // 使用插件
]
}
複製代碼
使用webpack-dev-server打包後,打開瀏覽器,頁面沒有index.htmljson
使用webpack打包的話,全部資源都存放在dist裏,index.html與圖片資源在一級目錄,因此經過/big.[hash].png能夠訪問到。瀏覽器