Babel-loader破坏了节点模块的Webpack源代码Map源代码

e0bqpujr  于 2022-11-13  发布在  Webpack
关注(0)|答案(1)|浏览(149)

在Webpack中使用babel-loader时,如果不排除node_modules,Webpack的源代码Map将(错误地)使用每个模块自己的源代码Map中列出的路径,而不是生成新的路径。
例如,我使用模块a,它的布局如下:

node_modules/
--a/
----dist/
------index.js
------index.js.map
----src/
------index.ts

在源代码Map中有"sources":["../src/index.ts"],这是合理和正确的。
然而,当Webpack使用这个时,'webpack:///../src/index.ts'将是源Map的sources之一。这不是一个TS项目,如果a的使用被注解掉,那么这个条目将消失,所以这个条目的来源不会混淆。
如果我将exclude: /node_modules/添加到babel-loader配置中,正确的源代码将显示为"webpack:///./node_modules/a/dist/index.js"
我该如何纠正这个问题呢?使用这些源代码Map是相当不可能的,因为它们包含了来自模块深处的相对路径。我没有办法知道在包含几十个模块的大型项目中,../src/index.ts实际上指的是什么。
Webpack配置:

const { resolve } = require('path');

module.exports = function() {
    return {
        module: {
            rules: [
                {
                    test: /\.m?[jt]sx?$/,
                    //exclude: /node_modules/,  // Uncommenting "fixes" the sources
                    loader: 'babel-loader',
                },
            ]
        },
        mode: 'production',
        devtool: 'source-map',

        output: {
            filename: 'ssr-bundle.js',
            path: resolve(__dirname, 'dist'),
            libraryTarget: 'commonjs2',
        },
        externals: {
            preact: 'preact'
        },
        target: 'node',
    }
}

用作复制材料的示例入口点:

import { h } from 'preact';
import { computed, signal } from '@preact/signals';

const currentState = signal('idle');
const isFormEnabled = computed(() => currentState.value !== 'loading');

export default function App() {
    return h('form', {}, [
        h('input', { type: 'text', disabled: !isFormEnabled.value })
    ]);
}

@preact/signals就是上面例子中的a。它并不重要,可以用任何东西替换。)

"@babel/core": "^7.19.1",
"babel-loader": "^8.2.5",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
p8ekf7hl

p8ekf7hl1#

我以前在使用node_modules的source map时遇到过一些麻烦。在做了一些实验后,我发现最好的解决方案是使用一个社区source-map-loader,而不是仅仅使用内置的source map。简而言之,你可能会发现使用这个设置可以正确地设置它:

{
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: "pre",
        use: ["source-map-loader"],
      },
    ],
  },
  // ...
}

相关问题