如何指定bundle.js.map(Source Map)文件路径至开发者工具?Parcel打包后Source Map路径错误及WebSocket连接CSP报错解决方案咨询
Let's work through your two Parcel-related problems one by one:
1. Fixing the Source Map Path for DevTools
The 404 error happens because Parcel defaults to setting the sourceMappingURL in bundle.js to point to the root directory (like /bundle.js.map), but your actual source map file lives in the /js/ subdirectory.
To correct this, you need to tell Parcel the proper public URL prefix for your bundled assets:
Using CLI commands directly: Add the
--public-urlflag when starting the dev server or running a build:# For development server parcel serve src/your-entry-file.js --public-url /js/ --out-dir public/js # For production build parcel build src/your-entry-file.js --public-url /js/ --out-dir public/jsThis will update the source map reference in
bundle.jsto//# sourceMappingURL=/js/bundle.js.map, so DevTools loads it from the correct path.Using package.json scripts: Add the flag to your npm scripts for easier reuse:
"scripts": { "dev": "parcel serve src/your-entry-file.js --public-url /js/ --out-dir public/js", "build": "parcel build src/your-entry-file.js --public-url /js/ --out-dir public/js" }
2. Resolving the CSP Violation from Parcel's WebSocket Code
That WebSocket connection code is automatically injected by Parcel's Hot Module Replacement (HMR) feature, which is enabled by default in development mode. The random port (55561 here) is a dynamically assigned port for Parcel's HMR server, which pushes code updates to your browser without needing a full page reload.
Here are your fixes:
Option 1: Update your Content Security Policy (for development)
Adjust your CSP to allow WebSocket connections to localhost ports. Modify your CSP header or meta tag to include:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; connect-src 'self' ws://localhost:*;">
The ws://localhost:* wildcard lets the browser connect to any localhost WebSocket port, which works since Parcel might use different random ports each time you start the dev server.
Option 2: Disable HMR (not recommended for development)
If you don't need live code reloading, you can turn off HMR with the --no-hmr flag:
parcel serve src/your-entry-file.js --no-hmr --public-url /js/ --out-dir public/js
Option 3: Use production build for deployment
If you see this error in a production environment, you're likely using the development server (parcel serve) instead of building for production. Run parcel build instead—Parcel automatically strips out HMR code from production bundles, so that WebSocket snippet won't exist at all.
内容的提问来源于stack exchange,提问作者Suresh D

