Rails+Webpacker环境下PhotoSwipe路径解析失败求助
Let's break down why you're hitting this ModuleNotFoundError and how to fix it step by step:
1. Ensure Your Variable Override Loads Before PhotoSwipe Styles
The most common issue here is variable loading order. If you're importing PhotoSwipe's CSS before your custom variables, your $pswp__assets-path override won't take effect—PhotoSwipe's default value will be used instead.
Fix your stylesheets.scss import order like this:
// First import your custom variables file (where $pswp__assets-path is defined) @import "../path/to/your/variables"; // Then import PhotoSwipe's core and default skin styles @import "photoswipe/dist/photoswipe.css"; @import "photoswipe/dist/default-skin/default-skin.css";
2. Set $pswp__assets-path to a Webpack-Recognizable Path
Webpack needs to know how to resolve paths to assets in Node modules. Use the ~ prefix to tell Webpack to look in your node_modules directory directly:
In your variables file:
// Point directly to the default-skin folder in PhotoSwipe's node module $pswp__assets-path: "~photoswipe/dist/default-skin/" !default;
The ~ is critical here—it tells Webpack to resolve the path starting from node_modules, instead of treating it as a relative path from your packs directory (which is why you were getting the error about not finding ./default-skin.png in /vagrant/app/webpacker/packs).
3. Verify Webpacker's Asset Loader Configuration
Make sure Webpacker is set up to handle image assets. Check your config/webpack/environment.js to ensure file-loader is configured correctly (it should be by default, but it's worth confirming):
const { environment } = require('@rails/webpacker'); // Ensure file-loader processes image files const fileLoader = environment.loaders.get('file'); fileLoader.exclude = /\.(js|mjs|jsx|ts|tsx|css|scss|sass)$/; environment.loaders.append('file', fileLoader); module.exports = environment;
4. Fallback: Copy Assets to Your Webpacker Assets Directory
If the above doesn't work for some reason, you can manually copy PhotoSwipe's image assets to your app's Webpacker assets folder:
- Copy all image files from
node_modules/photoswipe/dist/default-skin/toapp/webpacker/assets/images/photoswipe/ - Update your variable to point to this local path:
$pswp__assets-path: "../images/photoswipe/" !default;
Why Your Previous Attempts Failed
Chances are either:
- You were importing PhotoSwipe's styles before your variables (so your override didn't apply), or
- You weren't using the
~prefix, so Webpack was trying to resolve the path relative to yourpacksdirectory instead ofnode_modules.
内容的提问来源于stack exchange,提问作者rctneil

