在使用webpack-dev-server开发的时候,访问资源路径出了很多问题,挖了很多坑,找了一些资料,自己跟着敲了一下,现记录一下。
参考博客:
webpack 配置 publicPath的理解
这篇博客写的output里的publicPath,写的很详细很清楚了
webpack与webpack-dev-server
webpack新手入门的教程里,在写package.json
文件时,通常设置为:
"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两种情况。
手动创建html
- 创建项目目录
webpack-demo
|-src
|-index.js --入口文件
|-img
|-big.png
|-index.html --根页面
|-webpack.config.js
|-package.json
复制代码
- 各自写入测试代码
- 在根目录下手动创建Html
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webpack Tut</title>
</head>
<body>
</body>
</html>
复制代码
- 通过js动态创建图片
// 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文件,此时项目根目录有该文件所以就开始解析。
src="./dist/bundle.js"
,再重新打包查看,发现js文件已经加载成功,但是图片路径不对,图片是相对于根目录的,但是图片资源现在存在dist文件夹下。
puhcliPath:'/dist/'
,就可以访问到资源。
所以当有外部页面请求资源时,将publicPath与path的值设置为一样就可以了。
自动创建html
删除根目录下的index.html,然后安装html-webpack-plugin自动创建html.
// 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.html
使用webpack打包的话,所有资源都存放在dist里,index.html与图片资源在一级目录,所以通过/big.[hash].png可以访问到。