本文主要总结一下webpack里面关于path、publicPath和contentBase的区别及用法。css
- output里面的path表示的是output目录对应的一个绝对路径。
- output里面的publicPath表示的是打包生成的index.html文件里面引用资源的前缀
- devServer里面的publicPath表示的是打包生成的静态文件所在的位置(如果devServer里面的publicPath没有设置,则会认为是output里面设置的publicPath的值)
- devServer里面的contentBase表示的是告诉服务器从哪里提供内容。(只有想提供静态文件时才须要)
- src
- index.css
- index.js
- index.html
- package.json
- webpack.config.js
复制代码
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
module: {
rules: [
{
test: /\.css/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
}
]
},
devtool: 'source-map',
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: 'style.css'
}),
new webpack.HotModuleReplacementPlugin()
]
}
复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webpack-dev-server</title>
</head>
<body>
<div id="app">aaa</div>
</body>
</html>
复制代码
#app {
color: red;
}
复制代码
import './index.css'
复制代码
在里面添加两条命令html
"scripts": {
...,
"build": "webpack",
"dev": "webpack-dev-server --open chrome"
}
复制代码
下面经过例子来了解一下path、publicPath和contentBase的区别吧。webpack
output 属性告诉 webpack 在哪里输出它所建立的 bundles,以及如何命名这些文件,默认值为 ./dist。基本上,整个应用程序结构,都会被编译到你指定的输出路径的文件夹中。web
output里面的path很好理解,指的就是output目录对应的一个绝对路径。chrome
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist') // 输出目录对应的绝对路径
},
复制代码
运行npm run build 命令打包文件,能够看到打包以后的文件都输出到了dist文件夹。npm
output中的publicPath经常使用于在生产环境。它会为全部的资源指定一个基础路径。设置了publicPath后,会为资源添加一个前缀。 看例子: 将output中的配置改成:json
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'), // 输出目录对应的绝对路径
publicPath: '/outputdist/'
},
复制代码
运行npm run dev 命令 能够看到命令行显示以下信息: bash
由上面两张图能够看出,在output里面设置了publicPath之后,如果devServer里面没有设置publicPath,则使用webpack-dev-server 在进行打包时生成的静态文件所在的位置以及index.html文件里面引用资源的前缀都是output.publicPath里面设置的值服务器
添加devServer的配置:app
devServer: {
hot: true,
publicPath: '/dist/'
}
复制代码
而后运行npm run dev, 命令行显示以下信息:
能够看出devServer里面的publicPath表示的是打包生成的静态文件所在的位置。而且它的优先级是最高的。而publicPath表明的是index.html文件里面引用资源的前缀
添加contentBase的配置:
devServer: {
contentBase: './aaa', // 不设置的话,默认是当前执行的目录,通常是项目根目录。会在项目根目录查找index.html文件。
hot: true,
publicPath: '/dist/'
},
复制代码
而后运行npm run dev, 命令行显示以下信息:
更改一下配置:
devServer: {
contentBase: './src', // 不设置的话,默认是当前执行的目录,通常是项目根目录。会在项目根目录查找index.html文件。
hot: true,
publicPath: '/dist/'
},
复制代码
将contentBase设置为src目录,src目录里面是有index.html文件的。看一下执行结果。 运行npm run dev, 访问http://localhost:8080/结果显示: