使用babel-loader与Webpack一起使用,如果不排除node_modules,Webpack的源映射将(不正确)使用每个模块的源映射中列出的路径,而不是生成新的路径。
例如,我使用的是模块a,如下所示:
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配置:
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"发布于 2022-09-20 08:03:10
以前,我在使用node_modules的源地图时有过一些恼人的经历。然后,我想出了一个最好的解决方案,那就是使用一个社区source-map-loader,而不仅仅是在做了一些实验之后才使用内置的源代码映射,而不需要结果。简而言之,您可能会发现使用此设置正确地设置了它:
{
devtool: 'source-map',
module: {
rules: [
{
test: /\.js$/,
enforce: "pre",
use: ["source-map-loader"],
},
],
},
// ...
}https://stackoverflow.com/questions/73779799
复制相似问题