webpack output.publicPath

这篇文章用例子讲解我在webpack的学习过程中遇到的publicPath问题。

对于按需加载(on-demand-load)或加载外部资源(external resources)(如图片、文件等)来说,output.publicPath 是很重要的选项。如果指定了一个错误的值,则在加载这些资源时会收到 404 错误。创建项目目录如下:

index.js:

import './css/style.css'
import MyImage from './assets/bg.jpg'

function component(){
    const element = document.createElement('div')

    element.innerHTML = 'hello webpack'
    element.classList.add('hello')

    const img = document.createElement('img')
    img.src = MyImage

    document.body.appendChild(img)

    return element
}

document.body.appendChild(component())


webpack.config.js:

const path = require('path')

module.exports = {
    mode: 'development',
    context: path.resolve(__dirname, '../src'),
    entry: {
        app: './index.js'
    },
    output: {
        filename: '[name].bundle.js',
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    'file-loader'
                ]
            }
        ]
    }
}

style.css:

body{
    margin: 0;
}
.hello {
    color: red;
    height: 120px;
    background: url("../assets/bg.jpg") no-repeat;
    background-size: 100%;
    text-align: center;
}

img {
    width: 40px;
    height: 40px;
}

可知在index.js中通过import MyImage from './assets/bg.jpg',以及在style.css中通过background: url("../assets/bg.jpg") no-repeat;同时引用了图片bg.jpg。webpack.config.js中没有设置output.publicPath。运行webpack打包。打包后的目录如下:

查看浏览器运行结果:

结果发现图片并没有正常显示。检查network,可以看到图片的引用地址为file:///Users/lizuncong/Documents/webpack-demos/demo3-1/26f9c98952a19416da7a33221049f01c.jpg。明显不对的。查看app.bundle.js文件:

可以看到webpack运行函数中__webpack_require__.p = ""; 然后./assets/bg.jpg的导出路径为__webpack_require__.p + \"26f9c98952a19416da7a33221049f01c.jpg\"。

修改webpack.config.js,给output的设置publicPath: 'dist/'。并运行webpack。可以发现浏览器能正常显示图片了。

const path = require('path')

module.exports = {
    mode: 'development',
    context: path.resolve(__dirname, '../src'),
    entry: {
        app: './index.js'
    },
    output: {
        filename: '[name].bundle.js',
        publicPath: 'dist/'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
            {
                test: /\.(png|jpg|gif)$/,
                use: [
                    'file-loader'
                ]
            }
        ]
    }
}

观察app.bundle.js,可知__webpack_require__.p = "dist/";正是我们在output.publicPath中设置的值。

猜你喜欢

转载自blog.csdn.net/qq_20567691/article/details/84337919
今日推荐