在 scss 中引入具有相对路径的图像将导致 postcss 失效?

发布于 2022-09-11 15:21:33 字数 5192 浏览 23 评论 0

一开始,我在 webpack 中 配置了 postcss,可以生效,但是如果在 scss 中引入了背景图片,打包时就会报这样一个错误。所以我在 postcss 配置中添加了 publicPath ,发现不报错了,但是又引发了另一个新的问题,postcss 又不起作用了,出现了如下警告,能帮我看下如何正确配置吗?

scss 中引入背景图片出现的打包错误信息


Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js):
ModuleNotFoundError: Module not found: Error: Can't resolve 'assets/black-coffee.png' in '/Users/admin/Documents/zhike/github/myRepository/react-app/src/script/components/redux-test'
at factory.create (/Users/admin/Documents/zhike/github/myRepository/react-app/node_modules/webpack/lib/Compilation.js:814:10)

加入 publicPath配置属性 后的 postcss 失效警告

[0] dll vendor 12 bytes {vendor} [built]
+ 82 hidden modules
27% building modules 142/145 modules 3 active ..._modules/core-js/modules/_string-pad.jsYou did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.
49% building modules 333/336 modules 3 active ...ntime/helpers/interopRequireWildcard.jsYou did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.

刚开始是这样配置的

webpack.config.js


module.exports = {
  mode: process.env.NODE_ENV,
  entry: {
    bundle: ['@babel/polyfill', './src/script/app.js'],
  },
  output: {
    path: resolve('public'),
    filename: "bundle.js",
  },
  performance: {
    hints: false
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.(jsx?)$/,
        loader: 'eslint-loader',
        include: resolve('src'),
        options: {
          fix: true,
          cache: resolve('.cache/eslint'),
          failOnError: true,
          useEslintrc: true,
          configFile: resolve('.eslintrc.js'),
          formatter: require('eslint-friendly-formatter')
        }
      },
      {
        test: /\.js|jsx$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      }, {
        test: /\.scss/,
        use: [MiniCssExtractPlugin.loader, "css-loader?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]", {
          loader: 'postcss-loader',
          options: { ident: 'postcss', sourceMap: true, config: { path: resolve('postcss.config.js') }},
        }, "sass-loader"],
        exclude: resolve('node_modules'),
        include: resolve('src')
      }, {
        test: /\.css/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
      {
        test: /\.(png|jpe?g|bmp|gif|webp|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 8192,
          name: 'assets/img/[name].[hash:7].[ext]'
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 8192,
          name: 'assets/media/[name].[hash:7].[ext]'
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: "url-loader",
        options: {
          limit: 8192,
          name: 'assets/fonts/[name].[hash:7].[ext]'
        }
      }]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true,
    }),
    new webpack.DllReferencePlugin({
      context: path.join(__dirname, '..'),
      manifest
    }),
    new FriendlyErrorsWebpackPlugin({
      clearConsole: false,
      onErrors: (severity, errors) => {
        if (severity !== 'error') {
          return;
        }
        const error = errors[0];
        notifier.notify({
          title: 'Webpack error',
          message: `${severity}: ${error.name}`,
          subtitle: error.file || ''
        });
      }
    })
  ]
}

加上 publicPath 后的配置如下

webpack.config.js



module.exports = {
  // ...
  module: {
    rules: [
      //...
      {
        test: /\.js|jsx$/,
        exclude: /node_modules/,
        loader: "babel-loader"
      }, {
        test: /\.scss/,
        use: [MiniCssExtractPlugin.loader, "css-loader?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]", {
          loader: 'postcss-loader',
          options: { ident: 'postcss', sourceMap: true, config: { path: resolve('postcss.config.js') }, publicPath: '../'},
        }, "sass-loader"],
        exclude: resolve('node_modules'),
        include: resolve('src')
      }, {
        test: /\.css/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      }
      //...
      ]
  }
  //...
}

其他配置

postcss.config.js

module.exports = {
  plugins: [
    require("autoprefixer")({ browsers: ['last 2 versions'] }),
    require("cssnano")()
  ]
}

源码在这里,可以拉下代码运行看看:https://github.com/pdsuwwz/re...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十级心震 2022-09-18 15:21:33

请问有解决吗?

我遇到了相同的提示,不过我发现post-css实际是生效的。
比如查看浏览器样式,发现autoprefixer是生效的。而且我的less文件中引入相对路径的图片做背景,实际也是生效的,浏览器显示正常。

我觉得可能是错误的提示吗??

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文