Webpack dev-server的各个属性(static、publicPath)

2,863 阅读1分钟

1、static指定当前服务器的根目录是什么

代码如下所示:Webpack-Config

const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
module.exports = {
    entry:'./src/index.js',

    output:{
        filename:'bundle.js',
        path:path.resolve(__dirname,'./dist'),
        clean:true,
    },

    mode:'development',

    devtool:'inline-source-map',

    plugins:[
        new HtmlWebpackPlugin({
            template:'./index.html',
            filename:'app.html',
            inject:'body'
        })
    ],

    devServer:{
        static:'./dist'
    }
}

static属性的意思是:把.dist文件夹作为服务器的根目录。也就是说,你启动localhost:8080时,第一眼看到的目录,就是static里设置的目录。那么,刚刚说的dist文件是什么?注意:不是我们项目根目录的dist文件夹:

image.png

为什么这么说?我把dist文件夹里面的html内容改变了,但是浏览器里看不到任何变化:

image.png

那么,这个./dist在哪呢?其实它在内存中,我们根本看不到。这个dist文件夹,是从当前项目的entry开始,打包生成的文件夹。也就是说,我们只要改变了src下的原文件(也就是打包之前的文件),那么dist也会跟着改变,浏览器也会刷新:

image.png

总结:它设置就是:就是index.html所在的目录 www.jianshu.com/p/fc1341b72…

2、output中的publicPath

给所有的静态资源添加前缀。那么有哪些静态资源呢?

比如,html里的src标签:

执行webpack之后,会打包生成html文件,这个html文件里所有的src标签引用的地址,会加上publicPath:

image.png

image.png

再比如,css文件里设置背景图片:

image.png