如何使用vue-cli-service build命令复制src/assets/others至dist/others?
把src/assets/others复制到dist/others的方法
我来帮你搞定这个需求,用Vue CLI的vue-cli-service build命令实现文件复制,有两种常用的方式,你可以选适合自己的:
方法1:直接在vue.config.js里配置copy-webpack-plugin
Vue CLI本身就集成了copy-webpack-plugin,不用额外安装依赖。如果项目根目录还没有vue.config.js,先新建一个,然后添加以下配置:
Vue CLI 5.x版本写法
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ configureWebpack: { plugins: [ require('copy-webpack-plugin')({ patterns: [ { from: 'src/assets/others', // 源目录 to: 'others', // 目标目录(相对于dist根目录) toType: 'dir' } ] }) ] } })
Vue CLI 4.x及以下版本写法
如果你的Vue CLI版本比较老,不用defineConfig,直接写:
module.exports = { configureWebpack: { plugins: [ require('copy-webpack-plugin')({ patterns: [ { from: 'src/assets/others', to: 'others' } ] }) ] } }
写完配置后,重新运行vue-cli-service build,src/assets/others里的所有文件就会自动复制到dist/others里了。
方法2:用链式Webpack配置(chainWebpack)
如果你更喜欢用Webpack的链式API来调整配置,也可以这样写:
const { defineConfig } = require('@vue/cli-service') const CopyWebpackPlugin = require('copy-webpack-plugin') module.exports = defineConfig({ chainWebpack: config => { // 给这个复制任务起个名字,比如copy-others config.plugin('copy-others') .use(CopyWebpackPlugin, [{ patterns: [ { from: 'src/assets/others', to: 'others' } ] }]) } })
小提醒
- 如果
src/assets/others是空目录,默认不会在dist里生成空的others文件夹,要是需要生成的话,可以在pattern里加noErrorOnMissing: true和force: true参数 - 一般不用手动安装
copy-webpack-plugin,Vue CLI已经帮你集成好了对应版本,避免版本冲突
内容的提问来源于stack exchange,提问作者Lukasz Dynowski
相关产品推荐
相关产品推荐

