Vue+thinkJs博客网站(一)之vue多页面应用的webpack3配置

news/2024/4/27 22:28:33/文章来源:https://blog.csdn.net/weixin_34390996/article/details/88612493

一.项目简介

    本项目使用vue作为前端框架,thinkJs作为后端框架,构建个人博客网站,页面分为博客展示和后台管理,主要目的是学习使用thinkJs。现在只完成了主要的博客增删改功能,发现webpack的配置遇到了一些坑,这里先记录下。项目目录结构如下:
图片描述

其中system文件夹是前端vue项目的代码,博客展示页面与后台管理页面都在这里,打包成两个页面,具体webpack配置是本文重点。项目地址在这

二.搭建过程

安装nodejs后,首先安装thinkjs

npm install -g think-cli;
thinkjs new self_blog;
npm install;
npm start;

这样thinkJs项目初步搭建完成了,接下来创建vue项目。项目根目录下新建文件夹system。

npm install -g vue-cli
vue init webpack self_blog
cd self_blog
npm install
npm run dev

这样vue项目初步搭建完毕,接下来讲下这里vue的具体webpack配置。

三.webpack配置

项目前端页面分为博客的展示和后台管理,这里的思路是将sytem的src下面放后台管理页面,在sytem下新建blog文件夹,放前台展示页面,打包时生成两个html,实现webpack打包多页面应用。目录如下:
图片描述

1.webpack.base.conf.js的配置

使用vue-cli创建项目,npm run dev运行开发环境,会使用webpack-dev-server作为前端服务器,从而实现热加载。这样打包的文件只会在内存里,这里我的思路是直接生成到thinkJs项目的view目录下,通过服务端的路由返回给前端。这样只用启动后端的服务就行了,因为文件已经打包到服务端,前端也不存在跨域访问后端的问题了。所以这里就不需要配置devServer了,而是改变html与js等静态资源的生成目录。首先看下webpack.base.conf.js的代码:

"use strict";
const path = require("path");
const utils = require("./utils");
const config = require("../config");
const vueLoaderConfig = require("./vue-loader.conf");
const webpack = require("webpack");
const baseFileName = require("../package.json").name;
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const cleanWebpackPlugin = require("clean-webpack-plugin");
const AssetsPlugin = require("assets-webpack-plugin");
function resolve(dir) {return path.join(__dirname, "..", dir);
}module.exports = {context: path.resolve(__dirname, "../"),entry: {app: "./src/main.js",blog: "./blog/index.js"},output: {path: config.build.assetsRoot,filename: "[name].js",publicPath:process.env.NODE_ENV === "production"? config.build.assetsPublicPath: config.dev.assetsPublicPath},resolve: {extensions: [".js", ".vue", ".json"],alias: {vue$: "vue/dist/vue.esm.js","@": resolve("src")}},externals: {vue: "Vue","vue-router": "VueRouter",echarts: "echarts",ElementUI: "element-ui"},module: {rules: [{test: /\.vue$/,loader: "vue-loader",options: vueLoaderConfig},{test: /\.js$/,loader: "babel-loader",include: [resolve("src"),resolve("test"),resolve("node_modules/webpack-dev-server/client")]},{test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,loader: "url-loader",exclude: [resolve("src/icons")],options: {limit: 10000,name: utils.assetsPath(baseFileName + "https://segmentfault.com/img/[name].[hash:7].[ext]")}},{test: /\.svg$/,loader: "svg-sprite-loader",include: [resolve("src")],options: {symbolId: "icon-[name]"}},{test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,loader: "url-loader",options: {limit: 10000,name: utils.assetsPath(baseFileName + "/media/[name].[hash:7].[ext]")}},{test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,loader: "url-loader",options: {limit: 10000,name: utils.assetsPath(baseFileName + "/fonts/[name].[hash:7].[ext]")}}]},plugins: [new AssetsPlugin({filename: "build/webpack.assets.js",processOutput: function(assets) {return "window.WEBPACK_ASSETS=" + JSON.stringify(assets);}}),new webpack.optimize.CommonsChunkPlugin({name: "vendor",minChunks: function(module) {return (module.resource &&/\.js$/.test(module.resource) &&module.resource.indexOf(path.join(__dirname, "../node_modules")) === 0);}}),new webpack.optimize.CommonsChunkPlugin({name: "manifest",minChunks: Infinity}),new ExtractTextPlugin({filename: utils.assetsPath(baseFileName + "/css/[name].[contenthash].css"),allChunks: true}),// 编译前删除之前编译生成的静态资源new cleanWebpackPlugin(["www/static/self_blog", "view/blog"], {root: resolve("../")})],node: {setImmediate: false,dgram: "empty",fs: "empty",net: "empty",tls: "empty",child_process: "empty"}
};

首先需要改的是入口文件,因为是多页面应用,需要多个入口文件来保证打包成不同的chunk。我们知道正常vue-cli创建的但页面应用,会打包成三个chunk,分别是vendor.js(第三方依赖),manifest.js(异步加载的实现),app.js(业务代码)。这里新增一个入口文件,打包时就会生成名为blog.js的chunk,含有前台展示页面的js业务代码。

这里新增使用的clean-webpack-plugin,是为了每次编译后,删除之前生成的js,css等静态资源,否则因为这些资源不重名,就会一直堆在你生成的目录下。

此外一些第三方依赖,vue,elementUI什么的,我使用了cdn引入,这样打包时这些依赖不会打进去,进而减小的vendor.js的体积。具体做法就是配置里的externals定义这些依赖,然后在生成html的模板里用script标签直接引入cdn里的js。

注意一下,如果你开发时想用vue-devtool,需要引入vue.js,如果不用就引入vue.min.js。

2.webpack.dev.conf.js的配置

先看下代码:

"use strict";
const utils = require("./utils");
const webpack = require("webpack");
const config = require("../config");
const merge = require("webpack-merge");
const path = require("path");
const baseWebpackConfig = require("./webpack.base.conf");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const FriendlyErrorsPlugin = require("friendly-errors-webpack-plugin");
const portfinder = require("portfinder");const HOST = process.env.HOST;
const PORT = process.env.PORT && Number(process.env.PORT);
const baseFileName = require("../package.json").name;
function resolve(dir) {return path.join(__dirname, "..", dir);
}
const devWebpackConfig = merge(baseWebpackConfig, {module: {rules: utils.styleLoaders({sourceMap: config.dev.cssSourceMap,extract: true,usePostCSS: true})},// cheap-module-eval-source-map is faster for developmentdevtool: config.dev.devtool,output: {path: resolve(config.dev.assetsRoot),filename: "static/" + baseFileName + "/js/[name]-[hash:5].js",chunkFilename: "static/" + baseFileName + "/js/[name]-[id:5].js"},plugins: [new webpack.DefinePlugin({"process.env": require("../config/dev.env")}),// new webpack.HotModuleReplacementPlugin(),new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.new webpack.NoEmitOnErrorsPlugin(),// https://github.com/ampedandwired/html-webpack-pluginnew HtmlWebpackPlugin({filename: resolve(`../view/blog/index_index.html`),template: "./view/index.html",title: "博客管理系统",favicon: resolve("favicon.ico"),inject: true,chunks: ["manifest", "vendor", "app"]}),new HtmlWebpackPlugin({filename: resolve(`../view/blog/blog_index.html`),template: "./view/blog.html",title: "博客展示",inject: true,chunks: ["manifest", "vendor", "blog"]}),// copy custom static assetsnew CopyWebpackPlugin([{from: path.resolve(__dirname, "../static"),to: config.dev.assetsSubDirectory,ignore: [".*"]}])]
});
module.exports = devWebpackConfig;

这里我删掉了之前默认配置的devSever,以及module.exports直接导出devWebpackConfig。此外,因为打包生成目录的变化,我修改了output里面的path,filename,chunkFilename。使他们生成到self_blog根目录的www/static下面,这也是thinkJs静态资源的默认目录。需要注意下,filename指的是你的出口文件(app),以及通过codespliting生成的js(vendor,manifest)的文件名;chunkFilename定义的是一些懒加载组件打包后的js文件名。

下面需要添加的就是html-webpack-plugin,因为需要打包成两个html,所以使用两次这个插件。除了定义生成文件名(filename),html模板(template)等,还需要定义你这个html需要的chunk,这是跟单页面配置的一个区别。

除此之外,如果你想要开发环境打包时就分离出css,那么在使用utils.styleLoaders时,将extract置为true。因为这里的方法判断是开发环境才使用extract-text-plugin抽离css。

3.webpack.prod.conf.js的配置

prod的配置与dev差不多,生成文件目录也没变,只不过多了一些js,css压缩插件。

"use strict";
const path = require("path");
const utils = require("./utils");
const webpack = require("webpack");
const config = require("../config");
const merge = require("webpack-merge");
const baseWebpackConfig = require("./webpack.base.conf");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const OptimizeCSSPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const baseFileName = require("../package.json").name;
const env = require("../config/prod.env");
function resolve(dir) {return path.join(__dirname, "..", dir);
}
const webpackConfig = merge(baseWebpackConfig, {entry: {app: "./entry/entry-client-index",blog: "./entry/entry-client-blog"},module: {rules: utils.styleLoaders({sourceMap: config.build.productionSourceMap,extract: true,usePostCSS: true})},devtool: config.build.productionSourceMap ? config.build.devtool : false,output: {path: resolve(config.dev.assetsRoot),filename: "static/" + baseFileName + "/js/[name]-[chunkhash:5].js",chunkFilename: "static/" + baseFileName + "/js/[name]-[chunkhash:5].js"},plugins: [new webpack.DefinePlugin({"process.env": require("../config/prod.env"),"process.env.VUE_ENV": '"client"'}),new UglifyJsPlugin({uglifyOptions: {compress: {warnings: false}},sourceMap: config.build.productionSourceMap,parallel: true}),new webpack.optimize.OccurrenceOrderPlugin(),new webpack.LoaderOptionsPlugin({minimize: true}),// extract css into its own filenew ExtractTextPlugin({filename: utils.assetsPath(baseFileName + "/css/[name].[contenthash].css"),allChunks: true}),new HtmlWebpackPlugin({minify: {},chunksSortMode: "dependency",environment: process.env.NODE_ENV,filename: resolve(`../view/blog/index_index.html`),template: "./view/index.html",title: "博客管理系统",favicon: resolve("favicon.ico"),inject: true,chunks: ["manifest", "vendor", "app"]}),new HtmlWebpackPlugin({filename: resolve(`../view/blog/blog_index.html`),template: "./view/blog.html",title: "博客展示",favicon: resolve("favicon.ico"),inject: true,chunks: ["manifest", "vendor", "blog"]}),// Compress extracted CSS. We are using this plugin so that possible// duplicated CSS from different components can be deduped.new OptimizeCSSPlugin({cssProcessorOptions: config.build.productionSourceMap? { safe: true, map: { inline: false } }: { safe: true }}),]
});if (config.build.productionGzip) {const CompressionWebpackPlugin = require("compression-webpack-plugin");webpackConfig.plugins.push(new CompressionWebpackPlugin({asset: "[path].gz[query]",algorithm: "gzip",test: new RegExp("\\.(" + config.build.productionGzipExtensions.join("|") + ")$"),threshold: 10240,minRatio: 0.8}));
}if (config.build.bundleAnalyzerReport) {const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;webpackConfig.plugins.push(new BundleAnalyzerPlugin());
}module.exports = webpackConfig;

四.总结

具体可以看github上的代码

本次项目主要目的是练习thinkJs,这里先把前期webpack配置方面的东西简单说下,下一篇将会仔细讲下thinkJs的使用方法和特性。项目会继续更新,不少东西还没做完呢。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_728721.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LAMP网站平台的构建和PHP应用部署

LAMP是目前最成熟的一种企业网站应用模式,可提供动态web站点应用及开发环境构成组件:Linux 、Apache、MySQL、PHP/Perl/Python公司需求:搭建一台可以支持动态web站点 的网站,并且可以支持PHP语言开发的环境,通过PHP部署…

说说我平时用的几个学习网站(网址)吧,希望可以给你帮助

为什么80%的码农都做不了架构师?>>> 1.颜色表及html代码,平时用用到色彩可以查下:颜色查询 2.在线代码着色高亮,这个特别好用,我平时在云笔记上都用它,记得复制的时候全部都复制进去&#xff…

阿里云系列——3.网站备案初步核审(详细步骤)---2015-11.12

网站部署之~阿里云系列汇总 http://www.cnblogs.com/dunitian/p/4958462.html 流程图: 1.注册账号 进:https://beian.gein.cn/account/login.htm 注册一个账号,然后会收到邮件 立即备案 如何办理首次备案?如果您从未办理过备案&am…

什么样的网站才能让搜索引擎喜欢?

要做好一个网站,更多的重心而不是网站有多么好,而是网站的运营、网站的seo优化、网站的推广有没有做好。对于一个网站的发展来讲,怎么做好这一系列的工作才是最为重要的。搜索引擎都喜欢什么样的网站?怎么样做才能让搜索引擎爱上你…

大型网站技术架构(六)网站的伸缩性架构

2019独角兽企业重金招聘Python工程师标准>>> 网站系统的伸缩性架构最重要的技术手段就是使用服务器集群功能,通过不断地向集群中添加服务器来增强整个集群的处理能力。“伸”即网站的规模和服务器的规模总是在不断扩大。 1、网站架构的伸缩性设计 网站的…

centos下linux运行asp网站搭建配置-mono+nginx

一、首先安装一些需要的软件包 1、 首先更新CentOS上的软件包:yum –y update。 2、 安装一些需要的库: yum -y install gcc gcc-c bison pkgconfig glib2-devel gettext make libpng-devel libjpeg-devel libtiff-devel libexif-devel giflib-devel l…

站长基础知识,网站被镜像是好是坏,被恶意镜像怎么处理

网站被镜像一直以来,感觉这个问题应该不会出现在自己的网站,因为只是个小站应该不会被镜像吧,然而并不是这样,通过后台加速和服务器后台流量统计发现,网站流量非常异常(有时候pv上万)&#xff0…

超酷的测速网站Ookla SPEEDTEST

测试网速的工具、网站估计不少,在百度一搜都能搜出一大堆,下面介绍一个国外测试网速的网站,用户体验相当棒,感觉酷毙了,那些其它测试网速的网站跟这个比起来,简直弱毙了。这个网速测试网站就是:…

小虾视频网站广告屏蔽器 V 5.0

本软件用于屏蔽一些视频网站的广告,也具备屏蔽一些恶意网站的作用!如过你发现在电脑正常的情况下有些网友打开开,那是因为屏蔽的原因,只要单击一键还原广告就OK了!~ 打开软件后不要老是点击不然容易出错!要…

50-100台中小规模网站集群搭建实战项目(超实用企业集群)

【老男孩运维班期中搭建50-100台规模的集群实战】学员入学第8-12周,必须完成的中小型网站集群实战,老男孩linuxpython高薪运维班全员项目实战1、项目规划:搭建50-100台规模的集群实战设计2、开启7-8台虚拟机(kickstart无人值守装机…

知识点详解的一些网站搜罗

2019独角兽企业重金招聘Python工程师标准>>> NSTimer 使用 绝对超详细(2):http://blog.csdn.net/davidsph/article/details/7899731 iOS 随机数(Fixed):http://blog.csdn.net/ouyangtianhan/article/details/17464149 应用程序挂…

常见的网站服务器架构有哪些(转载)

常见的网站服务器架构有哪些(转载)简单说下以下的架构都是在假设已经优化过linux内核的情况下进行初级篇:(单机模式)假设配置:(Dual core 2.0GHz,4GB ram,SSD)基础框架:a…

版权黑洞:视觉中国关闭网站整改 全景网络已暂停服务

【TechWeb】 一天四次上热搜,致歉,视觉中国这次是真的触犯了众怒。 北京时间4月9日周二晚人类首张黑洞照片公布之后不久 ,有网友发现视觉中国将这张图片列为“版权所有”的编辑图片,称“此图片是编辑图片,如用于商业用…

将英文版的sharepoint网站模板转成中文Sharepoint可以使用的模板

微软提供了很多Sharepoint的网站模板:http://www.microsoft.com/technet/windowsserver/sharepoint/wssapps/templates/default.mspx但是很多都是英文版的,在中外sharepoint下不能使用,不能安装。这里有一个很酷的网站模板转换工具(.STP Lang…

如何给网站加入优雅的实时反爬虫策略

2019独角兽企业重金招聘Python工程师标准>>> 你的网站内容很有价值,希望被google,百度等正规搜索引擎爬虫收录,却不想让那些无节操的山寨爬虫把你的数据扒走坐享其成。本文将探讨如何在网站中加入优雅的反爬虫策略。 【思路】 反爬…

特大型网站技术架构脑图

为什么80%的码农都做不了架构师?>>> 转载于:https://my.oschina.net/dyxp/blog/348841

git 提及 修改_提及好友的网站是否有害?

git 提及 修改Heres an interesting problem I think Im faced with. A buddy of mine who owns a fantastic Ethiopian Restaurant here in Portland, OR is having a Jazz Dinner event. I was going to post a note about it in my blog, but then I realized, that if I …

基于centos 7搭建Nginx网站服务器(包含虚拟web主机的配置)

一 、Nginx服务基础 Nginx (engine x)专为性能优化而开发,其特点是占有内存少,它的稳定性和低系统资源消耗,以及对并发连接的高处理能力,(单台物理服务器可支持5000个并发请求)。事实上nginx的并发能力确实…

如何快速开发网站?

开发网站 ,一般是如下过程: 找美工画图进行图片切分开发人员添加内容 现在还用JSP来做网页,当然属于...那啥的事情。 今天看看不一样的体验,稍有HTML基础,马上就可以照葫芦画瓢了。 第一步:找美工画图&…

互联网大型网站架构演变——上

每天十五分钟,熟读一个技术点,水滴石穿,一切只为渴望更优秀的你! ————零声学院 架构演变第一步:物理分离 webserver 和数据库 最开始,由于某些想法,于是在互联网上搭建了一个网站&#xf…