webpack的css-loader和file-loader冲突?

给点阳光yh
  • 281

image.png
例子就是为了测试一下css-loader,结果发现css-loader和file-loader冲突,
如果我把file-loader注释了页面就正常显示,file-loader会对css里面的url的图片也会进行处理吗?

js里面只有一行代码引入css

webpack配置如下

const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
  mode: "development",
  entry: {
    main: path.resolve(__dirname, "src", "index"),
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: "/syh-app/",
    filename: "[name].js",
  },
  module: {
    rules: [
      {
        test: /\.(css)?$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.jpg?$/,
        use: {
          loader: "file-loader",
          options: {
            outputPath: "images/",
          },
        },
      },
    ],
  },
  resolve: {
    extensions: [".json", ".js", ".jsx"],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "src/index.html",
    }),
    new CleanWebpackPlugin(),
  ],
  devtool: "source-map",
  devServer: {
    host: "localhost",
    open: true,
    port: 8080,
    openPage: "syh-app/",
  },
};
回复
阅读 415
1 个回答
dl0906
  • -2
新手上路,请多包涵

file-loader一般不用来处理css资源吧。css文件一般用css-loader,style-loader或者MiniCssExtractPlugin插件。
css-loader里面的url资源使用url-loader进行打包,不使用css-loader

我贴一下我常用的webpack配置吧:

.css文件处理:

const commonCssLoader = [{
    loader: MiniCssExtractPlugin.loader,
    options: {
        publicPath: '../'
    }
}, 'css-loader', {
    loader: 'postcss-loader',
    options: {
        ident: 'postcss',
        plugins: () => [require('postcss-preset-env')()]
    }
}];

file-loader一般搭配url-loader和html-loader用来处理外部资源。其中file-loader用来打包非html/css/less/js/jpg/jpeg/png/gif的文件,比如字体,音视频的文件。

             {
                test: /\.(jpg|jpeg|png|gif)$/,
                use: [{
                    loader: 'url-loader',
                    options: {
                        limit: 8 * 1024,
                        esModule: false,
                        name: 'img_[hash:5].[ext]',
                        outputPath: 'images'
                    }
                }]
            }, {
                test: /\.html$/,
                use: ['html-loader']
            }, {
                exclude: /\.(jpg|jpeg|png|gif|html|css|js|less)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'media_[hash:5].[ext]',
                        outputPath: 'media'
                    }
                }]
            }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏