path用来指定资源打包输出的位置,publicPath用来指定用来在网络上访问的资源目录。
output.path和output.publicPath
output.path的默认值是dist。output.publicPath的默认值是‘/’。
示例1:
//webpack.config.jsoutput:{filename:'bundle.js',path:path.join(__dirname,'dist'),publicPath:'/path/to/js',},devServer:{static:{diectory:path.join(__dirname,'public'),publicPath:'/mm'}port:8889,}
上面的配置表示打包后的js文件在项目目录下的dist文件夹中,如果使用了webpack-dev-server,那么访问该js文件的URL就会是http://localhost:8889/path/to/js/bundle.js
devServer中的static.directory和static.publicPath
使用
directory指定的是被显示到浏览器上的文件的目录,它的值必须是绝对路径,可以用path.join连接。一般用来指定静态资源目录。默认值是public
告诉服务器从哪里提供内容。只有在你希望提供静态文件时才需要这样做。 —webpack中文文档
publicPath指定一个请求目录,当用户对该目录进行请求时返回的是directory指定的目录内容。
告诉服务器在哪个 URL 上提供 static.directory 的内容。 —webpack中文文档
示例2:
//webpack.config.jsdevServer:{static:{diectory:path.join(__dirname,'public'),publicPath:'/mm'}port:8889,}
上面的配置表示,当我在本地使用webpack-dev-server指令,并请求http://localhost:8889/mm/a.js时,返回的是当前项目目录下的public文件夹的a.js。
publicPath有三种形式
Host相关
以’/‘开始,以当前页面的主机host name(ip或域名之后)为基础路径,上面的示例1,2就是以这种格式写的,相对更好理解。
HTML相关
我们可以将publicPath指定为HTML的相关路径,在请求这些资源时会以当前页面所在的路径加上相对路径,构成实际请求的URL,
示例3:
//以http://localhost:8889/app/index.html为例publicPath:'' //实际请求路径是http://localhost:8889/app/xxxpublicPath:'./js' //实际请求路径是http://localhost:8889/app/js/xxxpublicPath:'../assets/' //实际请求路径是http://localhost:8889/assets/xxx
CDN相关
当静态资源放在CDN上时,由于其域名和当前页面域名不一致,需要以绝对路径的形式进行指定。当publicPath以协议头或相对协议的形式开始时,代表当前路径是CDN相关
示例4:
publicPath:'http://cdn.com/" //实际路径是http://cdn.com/xxxpublicPath:'https://cdn.com/" //实际路径是https://cdn.com/xxxpublicPath:'//cdn.com/assets/" //实际路径是//cdn.com/assets/xxx
启动webpack-dev-server并引用静态资源
- 项目根目录下创建新文件夹public,在里面创建一个css文件,名为style.css
- 配置output和devServer如下: ```javascript output: { filename: ‘[name].js’, path: path.join(__dirname, “dist”), },
devServer: { static:{ directory:path.join(__dirname,’public’), publicPath:’/public’ }, port: 8888, },
3. 在src的index.html中引入style.css```html<link rel="stylesheet" href="/public/style.css">
- 用html-webpack-plugin将index.html处理并输出到dist中
- 启动webpack-dev-server,可以看到style.css能够被正常引入并作用到了HTML标签上。
- 在production模式下打包生成dist,将dist和public文件一同放到服务器上
