修改vue-cli的public目录时遇路径解析错误的技术求助
Hey there, let's fix this issue step by step. The problem with your current config is that you're trying to point the HTML plugin's template to a directory instead of a specific file, and more importantly, you're not actually telling Vue CLI to use wwwroot as your new public directory. Here's how to do it properly:
1. Use Vue CLI's Built-in publicDir Config (Recommended)
If you're using Vue CLI 3.x or newer (which you almost certainly are if you created the project with vue-cli), there's a dedicated config option for this. Just update your vue.config.js (located in the ClientApp directory) to:
module.exports = { // Point to the sibling wwwroot directory relative to ClientApp publicDir: '../wwwroot' }
Important Steps to Follow:
- Move all contents from
ClientApp/public(includingindex.html,favicon.ico, etc.) to thewwwrootdirectory. - Restart your dev server to ensure the new config takes effect (old cache can cause issues otherwise).
This works because publicDir tells Vue CLI exactly which directory to use as the public assets folder—no need to mess with webpack chains directly.
2. Manual Webpack Configuration (For Older Vue CLI Versions)
If for some reason you can't use publicDir, you'll need to adjust the webpack config to copy assets from wwwroot and update the HTML template path:
First, install copy-webpack-plugin if it's not already included (Vue CLI usually has it by default, but double-check):
npm install copy-webpack-plugin --save-dev
Then update your vue.config.js:
const path = require('path') module.exports = { chainWebpack: config => { // Remove the default copy plugin that handles the original public directory config.plugins.delete('copy') // Add a new copy rule to pull assets from wwwroot config.plugin('copy') .use(require('copy-webpack-plugin'), [ { patterns: [ { from: path.resolve(__dirname, '../wwwroot'), to: config.output.get('assetsDir'), globOptions: { ignore: ['**/index.html'] // Let the HTML plugin handle this file separately } } ] } ]) // Update the HTML plugin to use the index.html from wwwroot config.plugin('html') .tap(args => { args[0].template = path.resolve(__dirname, '../wwwroot/index.html') return args }) } }
Why Your Original Config Failed
Your code was trying to set the HTML template to ../wwwroot, but the template parameter expects a path to a specific file (like index.html), not a directory. That's why webpack threw the "Can't resolve" error—it was looking for a file at that directory path, not the directory itself. Plus, you weren't configuring Vue CLI to treat wwwroot as the public asset folder, so none of your static files would have been copied over anyway.
内容的提问来源于stack exchange,提问作者Almis

