Webpack [url / file-loader]无法解析URL的相对路径

拉维·罗山(Ravi Roshan)

我在Webpack中遇到相对路径问题。让我尝试解释这种情况:

我在Workspace目录中有2个单独的项目

  1. 项目A [使用Gulp捆绑]:稳定且有效
  2. Project-B [使用Webpack捆绑]:新项目

由于两个项目都使用相同的样式,因此我想将项目A的SCSS文件(由标准变量,预定义布局,模态,类等组成)重用到项目B中

在此处输入图片说明

Now, if I am trying to import Project-A index.scss in Project-B index.scss as another partial [Commenting out the Background Image URL Depency], webpack is able to generate the required CSS output file.

// Import Project A SCSS [Common Varibles, Classes, Styling etc] 
@import "../../../../Project_A/assets/stylesheets/index";

But as Project-A's index.scss is further referring background images from the respective Relative-Path, the webpack build is throwing error

'File / dir not found in XYZ/Project-B/Source/Stylesheets'.

Exact Error Block :

ERROR in ./src/assets/stylesheets/index.scss Module build failed: ModuleNotFoundError: Module not found: Error: Cannot resolve 'file' or 'diWorkSpace\Project_B\src\assets\stylesheets

screenshot : **在此处输入图片说明**

I am not able to understand, why Webpack is not able to resolve the Relative path of assets inside Project-A and still looking inside 'Project B'.

Here is the Code-Repo URL for the simulated issue : https://github.com/raviroshan/webpack-build-issue/tree/master/WorkSpace

Steps to reproduce.

  1. Download the Repo.
  2. Browse inside Project_B folder, and do a NPM install.
  3. Run 'webpack'. It would build correctly as Relative Image URL code is commented out.
  4. Now put back the commented line of code : https://github.com/raviroshan/webpack-build-issue/blob/master/WorkSpace/Project_A/assets/stylesheets/index.scss#L27
Ravi Roshan

So, finally after so much struggle, got a proper SOLUTION.

It turns out to be an issue with CSS-loader i.e it is not able to resolve the URL with respective to current file.

使用resolve-url-loader解决了此问题。https://www.npmjs.com/package/resolve-url-loader

 // Old Loader Config in Webpack-entry
 loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap!sass-loader?sourceMap')

 // New [Fixed] Loader Config in Webpack-entry
 loader: ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap!resolve-url-loader!sass-loader?sourceMap')

这是使用解决方案更新的代码仓库:https : //github.com/raviroshan/webpack-build-issue

注意:不要省略-loader。Webpack.config.js应该始终使用加载程序名称的长格式(即-loader后缀)。

还有另一个名为resolve-url的软件包,Webpack可以将其与resolve-url-loader混淆。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章