欢迎访问 生活随笔!

ag凯发k8国际

当前位置: ag凯发k8国际 > 前端技术 > vue >内容正文

vue

vue.config.js配置 -ag凯发k8国际

发布时间:2024/10/12 vue 7 豆豆
ag凯发k8国际 收集整理的这篇文章主要介绍了 vue.config.js配置 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

原作者项目地址:https://github.com/staven630/vue-cli3-config

const path = require("path"); const webpack = require("webpack"); // const glob = require("glob-all"); // const purgecssplugin = require("purgecss-webpack-plugin"); const bundleanalyzerplugin = require("webpack-bundle-analyzer").bundleanalyzerplugin; // const uglifyjsplugin = require("uglifyjs-webpack-plugin"); // const compressionwebpackplugin = require("compression-webpack-plugin"); // const prerenderspaplugin = require("prerender-spa-plugin"); // const aliossplugin = require("webpack-oss"); const resolve = dir => path.join(__dirname, dir); const is_prod = ["production", "prod"].includes(process.env.node_env); // const spritesmithplugin = require('webpack-spritesmith') // let has_sprite = true// const productiongzipextensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;// const addstylusresource = rule => { // rule // .use("style-resouce") // .loader("style-resources-loader") // .options({ // patterns: [resolve("src/assets/stylus/variable.styl")] // }); // };// try { // let result = fs.readfilesync(path.resolve(__dirname, './icons.json'), 'utf8') // result = json.parse(result) // const files = fs.readdirsync(path.resolve(__dirname, './src/assets/icons')) // has_sprite = files && files.length ? files.some(item => { // let filename = item.tolocalelowercase().replace(/_/g, '-') // return !result[filename] // }) : false // } finally { // has_sprite = false // }// 雪碧图样式处理模板 // const spritesmithtemplate = function(data) { // // pc // let icons = {} // let tpl = `.ico { // display: inline-block; // background-image: ; // background-size: ${data.spritesheet.width}px ${data.spritesheet.height}px; // }`// data.sprites.foreach(sprite => { // const name = '' sprite.name.tolocalelowercase().replace(/_/g, '-') // icons[`${name}.png`] = true // tpl = `${tpl} // .ico-${name}{ // width: ${sprite.width}px; // height: ${sprite.height}px; // background-position: ${sprite.offset_x}px ${sprite.offset_y}px; // } // ` // })// fs.writefile( // path.resolve(__dirname, './icons.json'), // json.stringify(icons, null, 2), // (err, data) => {} // )// return tpl // } // const format = aliossplugin.getformat();module.exports = {publicpath: is_prod ? process.env.vue_app_public_path : "./", // 默认'/',部署应用包时的基本 url// outputdir: process.env.outputdir || 'dist', // 'dist', 生产环境构建文件的目录// assetsdir: "", // 相对于outputdir的静态资源(js、css、img、fonts)目录configurewebpack: config => {const plugins = [];if (is_prod) {// 去除多余css// plugins.push(// new purgecssplugin({// paths: glob.sync([resolve("./**/*.vue")]),// extractors: [// {// extractor: class extractor {// static extract(content) {// const validsection = content.replace(// / /gim,// ""// );// return validsection.match(/[a-za-z0-9-_:/] /g) || [];// }// },// extensions: ["html", "vue"]// }// ],// whitelist: ["html", "body"],// whitelistpatterns: [/el-.*/],// whitelistpatternschildren: [/^token/, /^pre/, /^code/]// })// );// plugins.push(// new uglifyjsplugin({// uglifyoptions: {// compress: {// warnings: false,// drop_console: true,// drop_debugger: false,// pure_funcs: ["console.log"] //移除console// }// },// sourcemap: false,// parallel: true// })// );// 利用splitchunks单独打包第三方模块// config.optimization = {// splitchunks: {// cachegroups: {// libs: {// name: "chunk-libs",// test: /[\\/]node_modules[\\/]/,// priority: 10,// chunks: "initial"// },// elementui: {// name: "chunk-elementui",// priority: 20,// test: /[\\/]node_modules[\\/]element-ui[\\/]/,// chunks: "all"// }// }// }// };// gzip// plugins.push(// new compressionwebpackplugin({// filename: "[path].gz[query]",// algorithm: "gzip",// test: productiongzipextensions,// threshold: 10240,// minratio: 0.8// })// );// 预加载// plugins.push(// new prerenderspaplugin({// staticdir: resolve("dist"),// routes: ["/"],// postprocess(ctx) {// ctx.route = ctx.originalroute;// ctx.html = ctx.html.split(/>[\s] <");// if (ctx.route.endswith(".html")) {// ctx.outputpath = path.join(__dirname, "dist", ctx.route);// }// return ctx;// },// minify: {// collapsebooleanattributes: true,// collapsewhitespace: true,// decodeentities: true,// keepclosingslash: true,// sortattributes: true// },// renderer: new prerenderspaplugin.puppeteerrenderer({// // 需要注入一个值,这样就可以检测页面当前是否是预渲染的// inject: {},// headless: false,// // 视图组件是在api请求获取所有必要数据后呈现的,因此我们在dom中存在“data view”属性后创建页面快照// renderafterdocumentevent: "render-event"// })// })// );// oss// plugins.push(// new aliossplugin({// accesskeyid: process.env.access_key_id,// accesskeysecret: process.env.access_key_secret,// region: process.env.region,// bucket: process.env.bucket,// prefix: process.env.prefix,// exclude: /.*\.html$/,// format// })// );}// config.externals = {// vue: "vue",// "element-ui": "element",// "vue-router": "vuerouter",// vuex: "vuex",// axios: "axios"// };// if (has_sprite) {// plugins.push(// new spritesmithplugin({// src: {// cwd: path.resolve(__dirname, './src/assets/icons/'), // 图标根路径// glob: '**/*.png' // 匹配任意 png 图标// },// target: {// image: path.resolve(__dirname, './src/assets/images/sprites.png'), // 生成雪碧图目标路径与名称// // 设置生成css背景及其定位的文件或方式// css: [// [// path.resolve(__dirname, './src/assets/scss/sprites.scss'),// {// format: 'function_based_template'// }// ]// ]// },// customtemplates: {// function_based_template: spritesmithtemplate// },// apioptions: {// cssimageref: '../images/sprites.png' // css文件中引用雪碧图的相对位置路径配置// },// spritesmithoptions: {// padding: 2// }// })// )// }config.plugins = [...config.plugins, ...plugins];},chainwebpack: config => {// 修复hmrconfig.resolve.symlinks(true);config.plugin("ignore").use(new webpack.contextreplacementplugin(/moment[/\\]locale$/, /zh-cn$/));// const cdn = {// // 访问https://unpkg.com/element-ui/lib/theme-chalk/index.css获取最新版本// css: ["//unpkg.com/element-ui@2.10.1/lib/theme-chalk/index.css"],// js: [// "//unpkg.com/vue@2.6.10/dist/vue.min.js", // 访问https://unpkg.com/vue/dist/vue.min.js获取最新版本// "//unpkg.com/vue-router@3.0.6/dist/vue-router.min.js",// "//unpkg.com/vuex@3.1.1/dist/vuex.min.js",// "//unpkg.com/axios@0.19.0/dist/axios.min.js",// "//unpkg.com/element-ui@2.10.1/lib/index.js"// ]// };config.plugin("html").tap(args => {// 修复 lazy loading routes errorargs[0].chunkssortmode = "none";// html中添加cdn// args[0].cdn = cdn;return args;});// 添加别名config.resolve.alias.set("vue$", "vue/dist/vue.esm.js").set("@", resolve("src")).set("@assets", resolve("src/assets")).set("@scss", resolve("src/assets/scss")).set("@components", resolve("src/components")).set("@plugins", resolve("src/plugins")).set("@views", resolve("src/views")).set("@router", resolve("src/router")).set("@store", resolve("src/store")).set("@layouts", resolve("src/layouts")).set("@static", resolve("src/static"));// 压缩图片// config.module// .rule("images")// .use("image-webpack-loader")// .loader("image-webpack-loader")// .options({// mozjpeg: { progressive: true, quality: 65 },// optipng: { enabled: false },// pngquant: { quality: [0.65, 0.90], speed: 4 },// gifsicle: { interlaced: false },// webp: { quality: 75 }// });// const types = ["vue-modules", "vue", "normal-modules", "normal"];// types.foreach(type =>// addstylusresource(config.module.rule("stylus").oneof(type))// );// 打包分析if (process.env.is_analyz) {config.plugin("webpack-report").use(bundleanalyzerplugin, [{analyzermode: "static"}]);}if (is_prod) {// config.optimization.delete("splitchunks");}return config;},css: {modules: false,extract: is_prod,sourcemap: false,loaderoptions: {scss: {// 向全局sass样式传入共享的全局变量, $src可以配置图片cdn前缀prependdata: `@import "@scss/config.scss";@import "@scss/variables.scss";@import "@scss/mixins.scss";@import "@scss/utils.scss";$src: "${process.env.vue_app_oss_src}";`}}},transpiledependencies: [],lintonsave: false,runtimecompiler: true, // 是否使用包含运行时编译器的 vue 构建版本productionsourcemap: !is_prod, // 生产环境的 source mapparallel: require("os").cpus().length > 1,pwa: {},devserver: {// overlay: { // 让浏览器 overlay 同时显示警告和错误// warnings: true,// errors: true// },// open: false, // 是否打开浏览器// host: "localhost",// port: "8080", // 代理断就// https: false,// hotonly: false, // 热更新proxy: {"/api": {target:"https://www.easy-mock.com/mock/5bc75b55dc36971c160cad1b/sheets", // 目标代理接口地址secure: false,changeorigin: true, // 开启代理,在本地创建一个虚拟服务端// ws: true, // 是否启用websocketspathrewrite: {"^/api": "/"}}}} };

我自己用正在用的配置:
//下面uglifyjsplugin 等模块要自己用 npm install 一下

const path = require("path"); const compressionwebpackplugin = require("compression-webpack-plugin"); const productiongzipextensions = ["js", "css"]; const debug = process.env.node_env !== "production"; const uglifyjsplugin = require("uglifyjs-webpack-plugin");const resolve = dir => path.join(__dirname, dir);const is_prod = ["production", "prod"].includes(process.env.node_env);const addstylusresource = rule => {rule.use("style-resouce").loader("style-resources-loader").options({patterns: [resolve("src/assets/stylus/variable.styl")]}); };module.exports = {publicpath: "./", // 根域上下文目录outputdir: "dist", // 构建输出目录assetsdir: "assets", // 静态资源目录 (js, css, img, fonts)lintonsave: false, // 是否开启eslint保存检测,有效值:ture | false | 'error'runtimecompiler: true, // 运行时版本是否需要编译transpiledependencies: [], // 默认babel-loader忽略mode_modules,这里可增加例外的依赖包名// productionsourcemap: false, // 是否在构建生产包时生成 sourcemap 文件,false将提高构建速度productionsourcemap: !is_prod, // 生产环境的 source mapconfigurewebpack: config => {// webpack配置,值位对象时会合并配置,为方法时会改写配置if (debug) {// 开发环境配置config.devtool = "cheap-module-eval-source-map";} else {config.plugins.push(new compressionwebpackplugin({algorithm: "gzip",test: new regexp("\\.(" productiongzipextensions.join("|") ")$"),threshold: 10240,minratio: 0.8}));config.plugins.push(new uglifyjsplugin({uglifyoptions: {compress: {// warnings: true,drop_console: true,drop_debugger: false,pure_funcs: ["console.log"] //移除console}},sourcemap: false,parallel: true}));// 生产环境配置}// object.assign(config, { // 开发生产共同配置// resolve: {// alias: {// '@': path.resolve(__dirname, './src'),// '@c': path.resolve(__dirname, './src/components'),// 'vue$': 'vue/dist/vue.esm.js'// }// }// })},chainwebpack: config => {// webpack链接api,用于生成和修改webapck配置,https://github.com/vuejs/vue-cli/blob/dev/docs/webpack.mdif (debug) {// 本地开发配置} else {// 生产开发配置const types = ["vue-modules", "vue", "normal-modules", "normal"];types.foreach(type =>addstylusresource(config.module.rule("stylus").oneof(type)));}},parallel: require("os").cpus().length > 1, // 构建时开启多进程处理babel编译pluginoptions: {// 第三方插件配置},pwa: {// 单页插件相关配置 https://github.com/vuejs/vue-cli/tree/dev/packages/@vue/cli-plugin-pwa},devserver: {open: true,host: "0.0.0.0",port: 80,https: false,hotonly: false,//跨域我这边是在后台处理的//proxy: {// // 配置跨域//"/api": {//target: "http://xxxxx/",//ws: true,//changorigin: true,//pathrewrite: {// "xxx": ""//}//}//},before: app => {}} };

总结

以上是ag凯发k8国际为你收集整理的vue.config.js配置的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得ag凯发k8国际网站内容还不错,欢迎将ag凯发k8国际推荐给好友。

  • 上一篇:
  • 下一篇:
网站地图