欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue-cli单页应用改成多页应用配置详解

程序员文章站 2023-02-24 08:33:58
前言 从接触vue开始用的是vue-cli直接搭建单页应用,参考配合着vue-router开发起来简直爽到吊炸天,但是由于项目越来越复杂了,单页用起来可能有点力不从心...

前言

从接触vue开始用的是vue-cli直接搭建单页应用,参考配合着vue-router开发起来简直爽到吊炸天,但是由于项目越来越复杂了,单页用起来可能有点力不从心,能不能弄成多页面呢,查了相关资料得到的结论是完全可以的,能多页面多入口,并且可以使用组件,还引入jquery,这简直完美了,这个demo是从我已经改造完成的项目中摘出来的,现在演示下怎么把基于vue2的vue-cli单页模板改造成多页面,并且多入口的项目。

技术栈

  1. vue: 2.0.1
  2. vue-resource:1.0.3
  3. vue-router:2.0.0
  4. webpack:1.13.2
  5. gulp:3.9.1
  6. es6

运行

git clone https://github.com/dawnyu/vue-cli-multipage.git
npm install 
npm run build
npm run dev

改造后的目录

vue-cli单页应用改成多页应用配置详解

可以多目录生成目标文件

公共的js和样式图标放到assets文件夹即可

修改点

build/utils.js

var path = require('path')
var config = require('../config')
var glob = require('glob')
 // 将样式提取到单独的css文件中,而不是打包到js文件或使用style标签插入在head标签中
var extracttextplugin = require('extract-text-webpack-plugin')

exports.assetspath = function(_path) {
 var assetssubdirectory = process.env.node_env === 'production' ?
 config.build.assetssubdirectory :
 config.dev.assetssubdirectory
 return path.posix.join(assetssubdirectory, _path)
}

exports.cssloaders = function(options) {
 options = options || {}
 // generate loader string to be used with extract text plugin
 function generateloaders(loaders) {
 var sourceloader = loaders.map(function(loader) {
  var extraparamchar
  if (/\?/.test(loader)) {
  loader = loader.replace(/\?/, '-loader?')
  extraparamchar = '&'
  } else {
  loader = loader + '-loader'
  extraparamchar = '?'
  }
  return loader + (options.sourcemap ? extraparamchar + 'sourcemap' : '')
 }).join('!')

 if (options.extract) {
  return extracttextplugin.extract('vue-style-loader', sourceloader)
 } else {
  return ['vue-style-loader', sourceloader].join('!')
 }
 }

 // http://vuejs.github.io/vue-loader/configurations/extract-css.html
 return {
 css: generateloaders(['css']),
 postcss: generateloaders(['css']),
 less: generateloaders(['css', 'less']),
 sass: generateloaders(['css', 'sass?indentedsyntax']),
 scss: generateloaders(['css', 'sass']),
 stylus: generateloaders(['css', 'stylus']),
 styl: generateloaders(['css', 'stylus'])
 }
}

// generate loaders for standalone style files (outside of .vue)
exports.styleloaders = function(options) {
 var output = []
 var loaders = exports.cssloaders(options)
 for (var extension in loaders) {
 var loader = loaders[extension]
 output.push({
  test: new regexp('\\.' + extension + '$'),
  loader: loader
 })
 }
 return output
}
//增加获取多入口的方法 注意 这个参数是个数组
exports.getentry = function(globpaths) {
 var entries = {},
 basename, tmp, pathname;
 for (globpath of globpaths) {
 glob.sync(globpath).foreach(function(entry) {
  basename = path.basename(entry, path.extname(entry));
  tmp = entry.split('/').splice(-3);
  pathname = tmp.splice(0, 1) + '/' + basename; // 正确输出js和html的路径
  entries[pathname] = entry;
 });
 }
 console.log(entries);
 return entries;
}

webpack.base.conf.js

var path = require('path')
var config = require('../config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils')
var projectroot = path.resolve(__dirname, '../') ///——driname当前目录
var chunks = object.keys(utils.getentry(['./src/module/**/*.js', './src/m/**/*.js']));
// 将样式提取到单独的css文件中,而不是打包到js文件或使用style标签插入在head标签中
var extracttextplugin = require('extract-text-webpack-plugin');
module.exports = {
 entry: utils.getentry(['./src/module/**/*.js', './src/m/**/*.js']),//传入需要打包的入口,我这里是pc端和手机端入口打到一个包里
 output: {
 path: config.build.assetsroot,
 publicpath: process.env.node_env === 'production' ? config.build.assetspublicpath : config.dev.assetspublicpath, //根名称可配置
 filename: '[name].js'
 },
 resolve: {
 extensions: ['', '.js', '.vue'],
 fallback: [path.join(__dirname, '../node_modules')],
 alias: {
  'src': path.resolve(__dirname, '../src'),
  'assets': path.resolve(__dirname, '../src/assets'),
  'components': path.resolve(__dirname, '../src/components'),
  'jquery': 'jquery'
 }
 },
 resolveloader: {
 fallback: [path.join(__dirname, '../node_modules')]
 },
 module: {
 loaders: [{
  test: /\.vue$/,
  loader: 'vue-loader'
  },
  {
  test: /\.js$/,
  loader: 'babel',
  include: projectroot,
  exclude: /node_modules/
  },
  {
  test: /\.json$/,
  loader: 'json'
  },
  {
  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  loader: 'url',
  query: {
   limit: 30000,
   name: utils.assetspath('img/[name].[hash:7].[ext]')
  }
  },
  {
  test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
  loader: 'url',
  query: {
   limit: 10000,
   name: utils.assetspath('fonts/[name].[hash:7].[ext]')
  }
  }
 ]
 },
 eslint: {
 formatter: require('eslint-friendly-formatter')
 },
 vue: {
 loaders: utils.cssloaders(),
 postcss: [
  require('autoprefixer')({
  browsers: ['last 2 versions']
  })
 ]
 },
 plugins: [
 // new webpack.optimize.commonschunkplugin('static/build.js'),
 // 提取公共模块
 new webpack.optimize.commonschunkplugin({
  name: 'vendors', // 公共模块的名称
  chunks: chunks, // chunks是需要提取的模块
  minchunks: chunks.length
 }),
 // 配置提取出的样式文件
 new extracttextplugin('css/[name].css'),
 //引入jqury
 new webpack.provideplugin({
  $: "jquery",
  jquery: "jquery"
 })
 ],
}

webpack.dev.conf.js

var config = require('../config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils')
var basewebpackconfig = require('./webpack.base.conf')
var htmlwebpackplugin = require('html-webpack-plugin')
 // add hot-reload related code to entry chunks
object.keys(basewebpackconfig.entry).foreach(function(name) {
 basewebpackconfig.entry[name] = ['./build/dev-client'].concat(basewebpackconfig.entry[name])
})

module.exports = merge(basewebpackconfig, {
 module: {
 loaders: utils.styleloaders({ sourcemap: config.dev.csssourcemap })
 },
 // eval-source-map is faster for development
 devtool: '#eval-source-map',
 plugins: [
 new webpack.defineplugin({
  'process.env': config.dev.env
 }),
 // https://github.com/glenjamin/webpack-hot-middleware#installation--usage
 new webpack.optimize.occurenceorderplugin(),
 new webpack.hotmodulereplacementplugin(),
 new webpack.noerrorsplugin(),
 // https://github.com/ampedandwired/html-webpack-plugin
 // new htmlwebpackplugin({
 // filename: 'index.html',
 // template: 'index.html',
 // inject: true
 // })
 ]
})

var pages = utils.getentry(['./src/module/**/*.html', './src/m/**/*.html']);


for (var pathname in pages) {


 // 配置生成的html文件,定义路径等
 var conf = {
 filename: pathname + '.html',
 template: pages[pathname], // 模板路径
 favicon: './src/assets/images/wechat.png',
 inject: true // js插入位置

 };


 if (pathname in module.exports.entry) {
 conf.chunks = ['vendors', pathname];
 conf.hash = true;
 }

 module.exports.plugins.push(new htmlwebpackplugin(conf));
}

webpack.prod.conf.js

var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var basewebpackconfig = require('./webpack.base.conf')
var extracttextplugin = require('extract-text-webpack-plugin')
var htmlwebpackplugin = require('html-webpack-plugin')
var env = process.env.node_env === 'testing' ?
 require('../config/test.env') :
 config.build.env

module.exports = merge(basewebpackconfig, {
 module: {
 loaders: utils.styleloaders({ sourcemap: config.build.productionsourcemap, extract: true })
 },
 devtool: config.build.productionsourcemap ? '#source-map' : false,
 output: {
 path: config.build.assetsroot,
 filename: utils.assetspath('js/[name].[chunkhash].js'),
 chunkfilename: utils.assetspath('js/[id].[chunkhash].js')
 },
 vue: {
 loaders: utils.cssloaders({
  sourcemap: config.build.productionsourcemap,
  extract: true
 })
 },
 plugins: [
 // http://vuejs.github.io/vue-loader/workflow/production.html
 new webpack.defineplugin({
  'process.env': env
 }),
 new webpack.optimize.uglifyjsplugin({
  compress: {
  warnings: false,
  drop_debugger: true,
  drop_console: true
  }
 }),
 new webpack.optimize.occurenceorderplugin(),
 // extract css into its own file
 new extracttextplugin(utils.assetspath('css/[name].[contenthash].css')),
 // generate dist index.html with correct asset hash for caching.
 // you can customize output by editing /index.html
 // see https://github.com/ampedandwired/html-webpack-plugin
 // new htmlwebpackplugin({
 // filename: process.env.node_env === 'testing' ?
 //  'index.html' : config.build.index,
 // template: 'index.html',
 // favicon: './src/assets/images/tjd.ico',
 // inject: true,
 // minify: {
 //  removecomments: true,
 //  collapsewhitespace: true,
 //  removeattributequotes: true
 //  // more options:
 //  // https://github.com/kangax/html-minifier#options-quick-reference
 // },
 // // necessary to consistently work with multiple chunks via commonschunkplugin
 // chunkssortmode: 'dependency'
 // }),
 // split vendor js into its own file
 new webpack.optimize.commonschunkplugin({
  name: 'vendor',
  minchunks: function(module, count) {
  // any required modules inside node_modules are extracted to vendor
  return (
   module.resource &&
   /\.js$/.test(module.resource) &&
   module.resource.indexof(
   path.join(__dirname, '../node_modules')
   ) === 0
  )
  }
 }),
 // extract webpack runtime and module manifest to its own file in order to
 // prevent vendor hash from being updated whenever app bundle is updated
 new webpack.optimize.commonschunkplugin({
  name: 'manifest',
  chunks: ['vendor']
 })
 ]
})

if (config.build.productiongzip) {
 var 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
 })
 )
}

var pages = utils.getentry(['./src/module/**/*.html', './src/m/**/*.html']);

for (var pathname in pages) {


 // 配置生成的html文件,定义路径等
 var conf = {
 filename: pathname + '.html',
 template: pages[pathname], // 模板路径
 favicon: './src/assets/images/wechat.png',
 inject: true // js插入位置

 };
 if (pathname in pages) {
 conf.chunks = ['vendors', pathname];
 conf.hash = true;
 }

 module.exports.plugins.push(new htmlwebpackplugin(conf));
}

git地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。