首页 > 网站 > WEB开发 > 正文

webpack file-loader 解析 css 文件中 background-image路径问题。

2024-04-27 15:08:35
字体:
来源:转载
供稿:网友

webpack file-loader 解析 CSS 文件中 background-image路径问题。

通过 webpack 的 file-loader 把 css 中的 background-image 图片提取出来构建到输出目录(例如dist或者build目录),发现图片被生成在了产出目录的根目录。

webpack.config.js文件配置

var webpack = require('webpack');var vue = require('vue-loader');var path = require('path');var HtmlWebpackPlugin = require('html-webpack-plugin'), ExtractTextPlugin = require('extract-text-webpack-plugin');module.exports = { //devtool: 'eval-source-map', entry: "./js/app.js", output: { path: './__build__', filename: 'js/shared.js', }, resolve: { alias: { 'src': path.resolve(__dirname, './resources'), 'vue': 'vue/dist/vue.min' } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [{ test: //.vue$/, loader: 'vue' }, { test: //.js$/, exclude: /node_modules|vue//dist|vue-router//|vue-loader//|vue-hot-reload-api///, loader: ['babel-loader'], query: { PResets: ['es2015'] } }, {test: //.json$/,loader: "json"}, {test: //.css$/, loader: "style!css" }, {test: //.less$/,loader: 'style!css!less'}, {test: //.(png|jpg|jpeg|gif|woff)$/, loader: 'url?limit=4192&name=[path][name].[ext]' },//limit参数,代表如果小于大约4k则会自动帮你压缩base64编码的图片 /*{ test: //.(png|jpe?g|gif|ico)(/?/S*)?$/, loader: 'file-loader', query: { name: 'img/[name].[ext]' } },*/ {test: //.(otf|eot|ttf)$/, loader: "file?prefix=font/" }, {test: //.svg$/, loader: "file" }] }, vue: { loaders: { css: ExtractTextPlugin.extract('css-loader?sourceMap'), sass: ExtractTextPlugin.extract('css-loader?sourceMap!sass-loader?sourceMap') } }, babel: { presets: ['es2015', 'stage-3'], plugins: ['transform-runtime'] }, plugins: [ new HtmlWebpackPlugin({ template: './index.html' }), new ExtractTextPlugin('[name]-[hash:3].css') ]};

以下两种方法都可使用

==url-loader配置(1)==

loaders: [ {test: //.(png|jpg|jpeg|gif|woff)$/, loader: 'url?limit=4192&name=[path][name].[ext]' },]

limit参数,代表如果小于大约4k则会自动帮你压缩成base64编码的图片,否则拷贝文件到生产目录

==url-loader配置(2)==

test: //.(png|jpe?g|gif|ico)(/?/S*)?$/, loader: 'file-loader', query: { name: 'img/[name].[ext]'}

直接将图片拷贝到生产目录

接下来就可以正常使用了!


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表