Webpack CSS-loader 背景图片加载错误

4

我正在处理一个Angular2+ES2015+Babel+Webpack项目,当在CSS文件中包含图像并使用css-loader时,遇到了问题,已经花费数小时来解决这个问题,但目前还没有成功:

ERROR in ./src/app/home/home.component.css
Module build failed: SyntaxError: /path/to/project/src/app/home/images/penguin.png: Unexpected character '�' (1:0)
> 1 | �PNG
    | ^
  2 | 
  3 | 
  4 | IHDR��>a�gAMA��7��!�IDATx��]xTEמ�B�"�)"��� ��T?@?�iRiD�tPA��)"���$��K���K���wτ���f��M6a���OHؽ3s�3gΜ93#���>���x��}����>���x�Ƅ&���f&�o>
                                                ��ɉI�O����#S�a-a
                                                                  �9�8!�W1<�)O�G�j��B�
    at Parser.pp.raise (/path/to/project/node_modules/babylon/lib/parser/location.js:22:13)
    at Parser.getTokenFromCode (/path/to/project/node_modules/babylon/lib/tokenizer/index.js:561:12)
    at Parser.readToken (/path/to/project/node_modules/babylon/lib/tokenizer/index.js:180:21)
    at Parser.readToken (/path/to/project/node_modules/babylon/lib/plugins/flow.js:164:22)
    at Parser.nextToken (/path/to/project/node_modules/babylon/lib/tokenizer/index.js:169:21)
    at Parser.parse (/path/to/project/node_modules/babylon/lib/parser/index.js:128:12)
    at parse (/path/to/project/node_modules/babylon/lib/index.js:47:47)
    at File.parse (/path/to/project/node_modules/babel-core/lib/transformation/file/index.js:517:34)
    at File.parseCode (/path/to/project/node_modules/babel-core/lib/transformation/file/index.js:603:20)
    at /path/to/project/node_modules/babel-core/lib/transformation/pipeline.js:49:12
    at File.wrap (/path/to/project/node_modules/babel-core/lib/transformation/file/index.js:563:16)
    at Pipeline.transform (/path/to/project/node_modules/babel-core/lib/transformation/pipeline.js:47:17)
    at Object.transformFileSync (/path/to/project/node_modules/babel-core/lib/api/node.js:144:10)
    at compile (/path/to/project/node_modules/babel-register/lib/node.js:129:20)
    at loader (/path/to/project/node_modules/babel-register/lib/node.js:158:14)
    at Object.require.extensions.(anonymous function) [as .js] (/path/to/project/node_modules/babel-register/lib/node.js:168:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/path/to/project/src/app/home/home.component.css:6:2430)
    at Module._compile (module.js:409:26)
    at Object.loaderContext.exec (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:88:7)
    at Object.module.exports (/path/to/project/node_modules/to-string-loader/src/to-string.js:6:54)

如果您搜索错误,您会在github问题和stackoverflow上找到类似的情况,但并非完全相同。所有这些情况都指出了缺少图像加载器(此处为png文件),但在我的情况下,我有一个完美地工作的加载器。如果在JS文件中直接要求require('../image/penguin.png'),它将被加载并导出到输出路径!我的流程和Webpack配置非常复杂,大规模且分裂成不同的文件,但这里是有趣的部分。
import config from './config';

{
  [...]
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        exclude: [/node_modules/],
        loader: 'eslint'
      },
      {
        test: /\.css$/,
        exclude: [/node_modules/],
        loader: 'postcss?pack=lint'
      }
    ],
    loaders: [
      {
        test: /\.js$/,
        exclude: [/node_modules/, /\.(spec|e2e)\.js$/],
        loaders: [
          'babel',
          'angular2-template'
        ]
      },
      {
        test: /\.css$/,
        exclude: [/node_modules/],
        loaders: [
          'to-string',
          'css?-import',
          'postcss?pack=process'
        ]
      },
      {
        test: /\.(png|jpe?g|gif)$/,
        loaders: [
          'url?limit=10000&name=assets/images/[name].[ext]?[hash:20]',
          'image-webpack?bypassOnDebug&optimizationLevel=6'
        ]
      },
      [...]
    ]
  },
  output: {
    path: resolve(config.paths.dist),
    publicPath: `http://${config.dev.host}:${config.dev.port}/`,
    filename: '[name].js',
    sourceMapFilename: '[name].map',
    chunkFilename: '[id].chunk.js'
  },
  [...]
}

以下是触发错误的CSS代码:

[...]
.post-image {
  height: 150px;
  background-image: url(./images/penguin.png);
  background-position: center center;
  background-repeat: no-repeat;
}

如果使用to-string-loader来处理CSS看起来很奇怪,那是因为angular2-template-loader允许直接将CSS内联到Angular2组件的stylesUrl中。
由于错误堆栈,似乎在css-loader完成工作后,png文件没有使用定义的loader(url!image-webpack)加载,而是使用babel-register加载?所以我console.log了css-loader的结果,发现了预期的图片require
[...]
exports.push([module.id, ".post-image{height:150px;background-image:url(" + require("./images/penguin.png") + ");background-position:50%;background-repeat:no-repeat}", ""]);

所以我让Babel忽略PNG文件。
{
  "presets": [
    "es2015",
    "angular2",
    "stage-3"
  ],
  "ignore": ["*.png"]
}

由于Babel忽略了图片,因此这会导致稍微不同的错误,但最终结果似乎是相同的:

ERROR in ./src/app/home/home.component.css
Module build failed: SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at loader (/path/to/project/node_modules/babel-register/lib/node.js:158:5)
    at Object.require.extensions.(anonymous function) [as .js] (/path/to/project/node_modules/babel-register/lib/node.js:168:7)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/path/to/project/src/app/home/home.component.css:6:2430)
    at Module._compile (module.js:409:26)
    at Object.loaderContext.exec (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:88:7)
    at Object.module.exports (/path/to/project/node_modules/to-string-loader/src/to-string.js:6:54)

我卡住了,一点头绪都没有。看起来只是在CSS文件上设置一个图像背景应该非常容易。

有什么想法吗?


我也在我的应用程序中遇到了“略有不同的错误”。使用angular2和webpack。 - Niraj
1个回答

4

终于搞定了。

问题源头出现在链的末尾:to-string-loader

这个加载器使用Loader.exec来处理css-loader的响应,但这段代码存在已知的问题

除了停止使用加载器外,该问题中可以找到一些解决方案。但是迄今为止最好的解决方案是创建一个特定的加载器,就像Mathias Raacke (@ooc)在另一个问题中所提议的那样

希望这能帮助其他人不要浪费这么多时间!


那么你的解决方案是什么?我有点困惑。 - josephnvu
你可以创建自己的自定义加载器,或者使用另一个加载器 - Julián Gutiérrez
你提供的链接中使用 css-to-string-loader 的解决方案对我很有帮助!谢谢! - thescientist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接