Webpack 文件加载器重复公共路径 [英] Webpack file-loader duplicate public path

查看:48
本文介绍了Webpack 文件加载器重复公共路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 url-loaderfile-loader 来打包我的 sass 文件,但是图像 url 有问题.

I'm using url-loader and file-loader to package up my sass files, but having an issue with image urls.

我已经尝试使用 resolve.alias 在应用程序的根目录中为我的图像目录设置别名,这样我就可以使用 url(~images/myimage.png)我的 sass 文件 - 这适用于 url-loader,但如果图像被 file-loader 拾取,它们将使用重复的公共路径输出,即 dist/dist/[hash].png - 无论我使用 ~ 还是相对路径,情况都是如此.如果我使用图像的绝对路径,它会起作用,但如果我的应用程序安装在子目录下,则会中断.

I've tried using resolve.alias to alias my images directory in the root of the application so I can use url(~images/myimage.png) in my sass files - this works fine with the url-loader, but if the images are picked up by file-loader they are output with a duplicate public path, i.e. dist/dist/[hash].png - this is the case whether I use ~ or a relative path. It works if I use an absolute path to my images, but then breaks if my app is mounted under a sub-directory.

目录结构:

- images/
- js/
- styles/
- webpack.config.js

Webpack 配置:

Webpack config:

module.exports = {
    entry: {
        app: './js/bootstrap'
    },

    output: {
        filename: 'bundle.js',
        path: 'dist',
        publicPath: 'dist/'
    },

    module: {
        loaders: [
            {
                test: /\.scss$/,
                loader: ExtractPlugin.extract('style', 'css!sass')
            },
            {
                test: /\.(gif|png|svg|jpe?g)$/i,
                loader: 'url',
                query: {
                    limit: 1000
                }
            }
        ]
    },

    resolve: {
        // add alias for application code directory
        alias:{
            js: path.resolve(__dirname, 'js'),
            styles: path.resolve(__dirname, 'styles'),
            images: path.resolve(__dirname, 'images')
        },
        extensions: ['', '.js', '.scss', '.png', '.svg', '.jpg', '.jpeg', '.gif']
    }
};

Sass 文件:

.some-class{
    background: url('~images/myimage.png') // url-loader works, file-loader doesn't
    background: url('../../../images/myimage.png') // url-loader works, file-loader doesn't
    background: url('/images/myimage.png') // both loaders work until app mounted under a sub-directory
}

希望我只是错过了一些愚蠢的东西!

Hopefully I'm just missing something stupid!

推荐答案

我找到了一个修复,在 ExtractPlugin 中覆盖 publicPath 是这样做的:

I found a fix, overriding publicPath in the ExtractPlugin was what did it:

ExtractPlugin.extract('style', 'css!sass', { publicPath: './' })

这篇关于Webpack 文件加载器重复公共路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆