【问题标题】:webpack css-loader: fails to load a png file referenced as url('path') inside a css filewebpack css-loader:无法在 css 文件中加载引用为 url('path') 的 png 文件
【发布时间】:2017-07-10 03:32:12
【问题描述】:

我正在迈出使用 webpack 的第一步……到目前为止还不是很成功。 在我的 .css 文件中,有一个用 url 定义的图像背景:

background-image: url("patterns/header-profile.png");

应用程序在启动时出现了惊人的崩溃,并出现此错误

ERROR in ./~/css-loader?"modules":true,"sourceMap":true,"importLoaders":1,"localIdentName":"[local]__[hash:base64:5]"}!./~/postcss-loader!./src/assets/css/in
spinia.css

Module not found: Error: Can't resolve 'patterns/header-profile.png' in 'C:\----  absolute path  ---\src\assets\css'

首先这是我的项目结构:

./src/
  --> assets
        --> patterns
              --> header-profile.png
        --> mystyle.css  // <-- sos: this is where background img is defined
--> index.html
--> index.tsx

其次,这是我的 webpack.config.json:

var webpack = require('webpack');
var path = require('path');

// variables
var isProduction = process.argv.indexOf('-p') >= 0;
var sourcePath = path.join(__dirname, './src');
var outPath = path.join(__dirname, './dist');

// plugins
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  context: sourcePath,
  entry: {
    main: './index.tsx',
    vendor: [
      'react',
      'react-dom',
      'react-redux',
      'react-router',
      'react-router-redux',
      'redux'
    ]
  },
  output: {
    path: outPath,
    publicPath: './',
    filename: 'bundle.js',
  },
  target: 'web',
  resolve: {
    extensions: ['.js', '.ts', '.tsx'],
    // Fix webpack's default behavior to not load packages with jsnext:main module
    // https://github.com/Microsoft/TypeScript/issues/11677 
    mainFields: ['main']
  },
  module: {
    loaders: [
      // .ts, .tsx
      {
        test: /\.tsx?$/,
        loader: isProduction
          ? 'awesome-typescript-loader?module=es6'
          : [
            'react-hot-loader',
            'awesome-typescript-loader'
          ]
      },
      // css 
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          publicPath: './',
          loader: [
            {
              loader: 'css-loader',
              query: {
                modules: true,
                sourceMap: !isProduction,
                importLoaders: 1,
                localIdentName: '[local]__[hash:base64:5]'
              }
            },
            {
              loader: 'postcss-loader'
            }
          ]
        })
      },
      // static assets 
      { test: /\.html$/, loader: 'html-loader' },
      { test: /\.png$/, loader: "url-loader?limit=10000" },
      { test: /\.jpg$/, loader:  'file-loader' },
    ],
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        context: sourcePath,
        postcss: [
          require('postcss-import')({ addDependencyTo: webpack }),
          require('postcss-url')(),
          require('postcss-cssnext')(),
          require('postcss-reporter')(),
          require('postcss-browser-reporter')({ disabled: isProduction }),
        ]
      }
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filename: 'vendor.bundle.js',
      minChunks: Infinity
    }),
    new webpack.optimize.AggressiveMergingPlugin(),
    new ExtractTextPlugin({
      filename: 'styles.css',
      disable: !isProduction
    }),
    new HtmlWebpackPlugin({
      template: 'index.html'
    })
  ],
  devServer: {
    contentBase: sourcePath,
    hot: true,
    stats: {
      warnings: false
    },
  },
  node: {
    // workaround for webpack-dev-server issue 
    // https://github.com/webpack/webpack-dev-server/issues/60#issuecomment-103411179
    fs: 'empty',
    net: 'empty'
  }
};

最后这就是我在索引 js 文件中要求 mystyle.css 的方式:

require('/assets/css/inspinia.css');

我查看了 stackoverflow、github 和 google。我看到其他人也遇到过类似的问题。但我不明白他们应用的各种解决方案(我是 webpack 的新手)。

任何帮助将不胜感激。

【问题讨论】:

  • Module not found: Error: Can't resolve 'patterns/header-profile.png' in 'C:\---- absolute path ---\src\assets\css' - 图片在css文件夹下吗? proj 结构没有这样显示...
  • 是的,它在css文件夹下...

标签: url webpack png css-loader


【解决方案1】:

这是我解决这个问题的方法,但我并没有真正理解它为什么解决了我的问题(只是改变了周围的属性......)。

首先在我的 webpack.config.json 文件中,我确保这个 publicPath 是绝对路径 ('/') 而不是相对路径 ('./')

{
  output:{
     publicPath: '/'
  }
}

其次,在我需要 mystyle.css 的 index.tsx 中,我确保它是相对路径:

require('./assets/css/mystyle.css')

最后在我引用图像的 mystyle.css 中,我确保它是绝对路径(......疯狂......)。例如,我会:

background: url("/patterns/header-profile.png")

它神奇地起作用了!

谁能解释一下这个配置背后的逻辑是什么,这将有助于我理解 webpack 是如何工作的,尤其是在涉及 css 文件、图像资源和绝对/相对路径时。

【讨论】:

    猜你喜欢
    • 2017-06-26
    • 2018-07-12
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2015-11-19
    • 2017-10-27
    • 1970-01-01
    相关资源
    最近更新 更多