在NuxtJS中如何在单个页面内导入原生JavaScript文件?
nuxt.config.js Head Section Hey there, sorry to hear you're stuck with loading local JS files in your Nuxt config while CDN scripts work fine. Let's break down the most common reasons and fixes for this:
1. Incorrect File Path (Most Likely Culprit)
Nuxt treats the static/ directory as the root for static assets—files here get copied directly to your dist folder without processing. If you're referencing a local JS file, you need to use the absolute path relative to this root.
For example, if your file lives at static/js/custom-script.js, your head config should look like this:
export default { head: { script: [ // Use absolute path starting with /, omit the "static/" part { src: '/js/custom-script.js', body: true } // Add body: true if you want it loaded before </body> ] } }
If you used a relative path like ./static/js/... or missed the leading /, Nuxt won't resolve it correctly.
2. Using assets/ Instead of static/ for Unprocessed Scripts
If your JS file is in the assets/ directory, it's meant to be processed by Webpack (for minification, transpiling ES6+, etc.). Directly referencing it in the head section won't work because Webpack renames these files during build.
Instead, use Nuxt's plugin system to load it properly:
- Move your script to
plugins/(e.g.,plugins/custom-script.js) - Update
nuxt.config.js:
export default { plugins: [ // Load only on the client side (since it's a browser-only script) { src: '~/plugins/custom-script.js', mode: 'client' } ] }
3. Browser or Server Caching
Sometimes the issue is just stale cache:
- Clear your browser's cache (Ctrl+Shift+R on Windows/Linux, Cmd+Shift+R on Mac)
- Restart your Nuxt development server (
npm run devagain) - For production builds, try rebuilding your project from scratch (
rm -rf .nuxt && npm run build)
4. File Permissions or Case Sensitivity
- On Linux/macOS, file paths are case-sensitive—make sure your
srcpath matches the exact filename (e.g.,Custom-Script.jsvscustom-script.jsmatters) - Ensure your local JS file has read permissions (run
chmod +r path/to/your/file.jsif needed)
Quick Checklist
- Verify the file exists at the path you're referencing
- Use an absolute path starting with
/for files instatic/ - Use plugins for scripts in
assets/that need Webpack processing - Clear cache and restart the server
Hope one of these fixes gets your local JS file loading smoothly!
内容的提问来源于stack exchange,提问作者Leeqi7

