Webpack sass-loader 未生成正确的源映射

问题描述 投票:0回答:1

我有一个包含 sass-loader 的 webpack 配置。当我删除 sass-loader 时,我可以看到正确生成的源映射。但是当我添加 sass-loader 后源映射就损坏了。

    entry: {
      index: './src/index.tsx',
      'second-entry': './src/second-entry.ts',
    },
    devtool: 'source-map',
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: '[name].js',
    },
    module: {
      rules: [
        babelRule,
        {
          test: /\.s?css$/,
          use: [
            MiniCssExtractPlugin.loader,// "style-loader",
            { loader: 'css-loader', options: { sourceMap: true } },
            { loader: 'sass-loader',  options: { sourceMap: true }, },
          ],
        },
      ],
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: './src/editor-index.html',
        filename: 'editor-index.html',
        chunks: ['index'], // Specify the chunks to include in the HTML
      }),
      new MiniCssExtractPlugin({}),
    ],

我已经尝试使用 style-loader 和 MiniCSSExtract,我尝试了几个 devtool 选项。全部给出相同的错误。

无法加载 webpack://editify-v2/src/styles/delete.scss 的内容 (获取目标失败:不支持的 URL 方案;后备:HTTP 错误:状态代码 404,net::ERR_UNKNOWN_URL_SCHEME)

enter image description here

使用sass-loader生成index.css.map(缺少sourceContent)

{
    "version": 3,
    "file": "index.css",
    "mappings": ";;;AACE;EACE;AAAJ,C;;;;ACFA;EACE;AACF,C",
    "sources": ["webpack://editify-v2/./src/styles/delete.scss", "webpack://editify-v2/./src/styles/main.css"],
    "names": [],
    "sourceRoot": ""
}

没有 sass-loader 的正确源映射

{
    "version": 3,
    "file": "index.css",
    "mappings": ";;;AAAA;EACE;IACE,uBAAuB;;EAEzB;AACF;;;;;ACLA;EACE,YAAY;AACd",
    "sources": ["webpack://editify-v2/./src/styles/delete.scss", "webpack://editify-v2/./src/styles/main.css"],
    "sourcesContent": [".button {\n  div{\n    background-color: 'red';\n\n  }\n}\n", ".app {\n  color: green;\n}\n"],
    "names": [],
    "sourceRoot": ""
}

这是我的版本

  "devDependencies": {
    "babel-loader": "^9.1.3",
    "css-loader": "^6.8.1",
    "html-webpack-plugin": "^5.5.3",
    "mini-css-extract-plugin": "^2.8.1",
    "postcss-loader": "^8.1.1",
    "sass": "^1.80.6",
    "sass-loader": "^16.0.3",
    "style-loader": "^3.3.3",
    "webpack": "^5.88.2",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1",
  }

注意我没有使用node-sass,而是使用sass。(Webpacks 官方文档建议使用node-sass,但已弃用)。

webpack sass css-loader webpack-style-loader sass-loader
1个回答
0
投票

sass-loader
>= 16.0.0 起,源映射中的 sourceContent 生成被禁用。

解决方案

sass-loader
选项中添加
sassOptions.sourceMapIncludeSources
选项:

  {
    test: /\.s?css$/,
    use: [
      MiniCssExtractPlugin.loader,// "style-loader",
      { loader: 'css-loader', options: { sourceMap: true } },
      // include the sources in the generated source map, required since sass-loader >= 16.0.0
      { loader: 'sass-loader',  options: { sassOptions: { sourceMapIncludeSources: true } } },
    ],
  },

© www.soinside.com 2019 - 2024. All rights reserved.