4

我正在迈出使用 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'
  }
};

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

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

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

任何帮助将不胜感激。

4

1 回答 1

0

这是我在没有真正理解为什么它解决了我的问题的情况下解决这个问题的方式(只是改变了周围的属性......)。

首先在我的 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-02-20T19:56:30.937 回答