本文共 3192 字,大约阅读时间需要 10 分钟。
Vue CLI 3.0 是 Vue 的一大升级,相比前一代,它在构建工具和配置上有了显著改进。以下将对 Vue CLI 3.0 的配置进行详细总结,结合 webpack 的使用场景,帮助开发者更好地理解和应用这些配置。
Vue CLI 3.0 的配置文件通常位于项目根目录下的 vue.config.js
或 webpack.config.js
,具体配置如下:
module.exports = { // 部署应用时的基本 URL baseUrl: process.env.NODE_ENV === 'production' ? '192.168.60.110:8080' : '192.168.60.110:8080', // build时构建文件的目录 outputDir: 'dist', // build时放置生成的静态资源 (js、css、img、fonts) 的目录 assetsDir: '', // 指定生成的 index.html 的输出路径 indexPath: 'index.html', // 默认在生成的静态资源文件名中包含 hash filenameHashing: true, // 构建多页面应用的页面配置 pages: { index: { entry: 'src/index/main.js', template: 'public/index.html', filename: 'index.html', title: 'Index Page', chunks: ['chunk-vendors', 'chunk-common', 'index'] }, // 其他页面配置,可按需添加 'subpage': 'src/subpage/main.js' }, // 是否在开发环境下通过 eslint-loader 在每次保存时 lint 代码 lintOnSave: process.env.NODE_ENV !== 'production', // 是否使用包含运行时编译器的 Vue 构建版本 runtimeCompiler: false, // Babel 显式转译列表 transpileDependencies: [], // 是否需要生产环境的 source map productionSourceMap: true, // 设置生成的 HTML 中 和
在实际项目中,以下是一些常用的配置技巧:
baseUrl
:用于定义项目的基础 URL,通常用于部署时的路径配置。outputDir
:指定构建输出目录,建议将其设置为项目根目录或子目录。assetsDir
:在构建时,指定静态资源的存储目录,支持相对路径。indexPath
:定义生成的 index.html
文件路径,通常建议保留默认值。filenameHashing
:为生成的文件加上 hash,避免浏览器缓存问题。pages
:用于多页面应用的配置,支持单页应用和多页应用混合使用。runtimeCompiler
:开启或关闭 Vue 的运行时编译器,建议根据项目需求选择。transpileDependencies
:指定需要显式转译的依赖模块,通常用于第三方库。productionSourceMap
:决定是否在生产环境下生成 source map 文件。css
:负责 CSS 文件的处理,包括提取和 source map 等。devServer
:配置开发服务器,支持 hot-reload 和 HTTPS。pwa
:用于构建 Progressive Web App(PWA),支持 service worker 等特性。在实际使用过程中,可能会遇到以下问题:
crossOrigin
和 in integrity
属性,确保资源加载正常。以下是一个典型的 Vue CLI 3.0 配置示例(基于 webpack):
module.exports = { // baseUrl配置,根据项目实际部署路径调整 baseUrl: process.env.NODE_ENV === 'production' ? 'http://example.com' : '', outputDir: 'dist', assetsDir: 'src/assets', indexPath: 'index.html', filenameHashing: true, pages: { index: { entry: 'src/index/main.js', template: 'src/index.html', filename: 'index.html', title: '项目主页', chunks: ['chunk-vendors', 'chunk-common', 'index'] }, otherPage: { entry: 'src/other/main.js', template: 'src/other.html', filename: 'other.html', title: '其他页面' } }, lintOnSave: true, runtimeCompiler: false, transpileDependencies: [], productionSourceMap: true, css: { extract: false, sourceMap: false, loaderOptions: { css: {}, less: {} } }, devServer: { host: 'localhost', port: 8080, hot: true, https: true, proxy: { '/api': { target: 'http://backend.com', changeOrigin: true } } }, pwa: { workbox: { generateSW: true, swPath: 'sw.js' } }}
通过合理配置 Vue CLI 3.0 和 webpack,可以显著提升项目的构建效率和性能,满足不同项目的需求。
转载地址:http://fbox.baihongyu.com/