首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >巴贝尔-装载机损坏Webpack的node_modules源地图源

巴贝尔-装载机损坏Webpack的node_modules源地图源
EN

Stack Overflow用户
提问于 2022-09-19 22:14:26
回答 1查看 24关注 0票数 1

使用babel-loader与Webpack一起使用,如果不排除node_modules,Webpack的源映射将(不正确)使用每个模块的源映射中列出的路径,而不是生成新的路径。

例如,我使用的是模块a,如下所示:

代码语言:javascript
复制
node_modules/
--a/
----dist/
------index.js
------index.js.map
----src/
------index.ts

在该源地图中有"sources":["../src/index.ts"],这是合理和正确的。

然而,当Webpack消费这个,'webpack:///../src/index.ts'将是源地图的sources之一。这不是TS项目,如果注释掉了a的使用,条目就会消失,因此对于该条目的来源没有任何混淆。

如果要将exclude: /node_modules/添加到babel-loader配置中,则正确的源将显示为"webpack:///./node_modules/a/dist/index.js"

我该怎么纠正呢?使用这些源映射是不可能的,因为它们包含来自模块深处的相对路径。我无法知道有几十个模块的大型项目,../src/index.ts实际上指的是什么。

Webpack配置:

代码语言:javascript
复制
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',
    }
}

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

代码语言:javascript
复制
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。这不重要,可以用任何东西来交换。)

代码语言:javascript
复制
"@babel/core": "^7.19.1",
"babel-loader": "^8.2.5",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0"
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-20 08:03:10

以前,我在使用node_modules的源地图时有过一些恼人的经历。然后,我想出了一个最好的解决方案,那就是使用一个社区source-map-loader,而不仅仅是在做了一些实验之后才使用内置的源代码映射,而不需要结果。简而言之,您可能会发现使用此设置正确地设置了它:

代码语言:javascript
复制
{
  devtool: 'source-map',
  module: {
    rules: [
      {
        test: /\.js$/,
        enforce: "pre",
        use: ["source-map-loader"],
      },
    ],
  },
  // ...
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73779799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档