vue项目中多个入口的配置

时间:2023-03-10 08:14:15
vue项目中多个入口的配置

出处:http://www.qingpingshan.com/jb/javascript/221105.html

基于vue2.0生成项目,一段时间都在找如何配置成多个页面的。网上有这样的例子相对也是比较详细的,但是还是有些许不一样的地方的。所以,我还是记录下来,当然我也是参考了网上的资料的。

当然先来个vue的项目,打开命令行工具,对边进入一个目录下。

vue init webpack my-project

注意,node和npm的版本,npm版本最好是3.0+的。其中my-project是自定义的项目名,按照步骤一步一步来就好了,然后进入自动生成的文件夹下,下载依赖的包,然后运行,应该会打开浏览器的localhost:8080。

npm install
npm run dev

如果不出意外是能够打开页面的。

然后你就可以在项目的基础上开心的写组件了,那么我们应该怎么修改vue的配置,让我们的项目是多个页面的呢。

第一步

在index.html同级目录下新增一个页面,welcome.html,然后在src目录下,添加Welcome.vue和welcom_main.js。

第二步修改配置,配置项有4个文件:

build//文件夹下
webpack.base.conf.js
webpack.dev.conf.js
webpack.pro.conf.js
config文件夹下
index.js

其中所有的配置,有index的地方,都需要在复制一份。

比如index.js中:

build:{
play:path.resolve(__dirname, '../dist/welcome.html'), //新增的配置
}

webpack.base.conf.js中

entry:{
welcome: './src/welcome_main.js', //新增的配置
}

其他配置文件里的改动都类似。复制粘贴,然后改吧改吧就好了。

配置完后,运行下 npm run dev

不过这种方式的多页面配置,每次新加一个页面,必须重新配置一次,比较麻烦,如果页面不多,倒也是可行的,但是如果随着项目越来越多,到时候项目目录就很不简洁了。

所以,还有一种一劳永逸的方式。原理其实一样的,不过是文件的配置让文件自动生成。

项目生成方式还是一样,接下来的配置有点不同。

第一步:安装一个包glob 很重要的包

npm install  glob --save-dev

第二步配置config下面的index.js文件

var path = require('path')
var glob = require('glob') var build = {
env: require('./prod.env'),
//index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
bundleAnalyzerReport: process.env.npm_config_report
} //根据getEntry获取所有入口主页面
var pages = getEntry('src/pages/**/*.html'); //每个入口页面生成一个入口添加到build中
for (var pathname in pages) {
build[pathname] = path.resolve(__dirname, '../dist/' + pathname + '.html')
} module.exports = {
build: build,//生成的配置build
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: false,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
cssSourceMap: false
}
} //获取所有入口文件
function getEntry(globPath) {
var entries = {},
basename; glob.sync(globPath).forEach(function(entry) { basename = path.basename(entry, path.extname(entry));
entries[basename] = entry;
});
return entries;
}

这样就配置完了index.js了。

然后是配置webpack.base.conf.js

var path = require('path')
var glob = require('glob')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
var entries = getEntry('./src/pages/**/*.js') function resolve(dir) {
return path.join(__dirname, '..', dir)
} module.exports = {
entry: entries,
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'],
modules: [
resolve('src'),
resolve('node_modules')
],
alias: {
'vue$': 'vue/dist/vue.common.js',
'src': resolve('src'),
'assets': resolve('src/assets'),
'components': resolve('src/components')
}
},
module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
}, {
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
}, {
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
}, {
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}]
}
} //获取入口js文件
function getEntry(globPath) {
var entries = {},
basename, tmp, pathname; glob.sync(globPath).forEach(function(entry) {
basename = path.basename(entry, path.extname(entry));
pathname = basename.split("_")[0];
entries[pathname] = entry;
});
return entries;
}

这个文件主要是配置entry: entries入口js。具体就不多说了,剩下的两个配置文件类似。我直接复制代码了。

webpack.dev.conf.js文件的配置

var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
var glob = require('glob')
var path = require('path') Object.keys(baseWebpackConfig.entry).forEach(function(name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
}) module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new FriendlyErrorsPlugin(),
]
}) function getEntry(globPath) {
var entries = {},
basename; glob.sync(globPath).forEach(function(entry) { basename = path.basename(entry, path.extname(entry));
entries[basename] = entry;
});
return entries;
} var pages = getEntry('src/pages/**/*.html'); for (var pathname in pages) {
// 配置生成的html文件,定义路径等
var conf = {
filename: pathname + '.html',
template: pages[pathname], // 模板路径
inject: true, // js插入位置
chunks: [pathname]
};
module.exports.plugins.push(new HtmlWebpackPlugin(conf));
}

webpack.prod.conf.js文件的配置

var path = require('path')
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var env = config.build.env var plugins = [
new webpack.DefinePlugin({
'process.env': env
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new ExtractTextPlugin(utils.assetsPath('css/[name].[contenthash].css')),
] function getEntry(globPath) {
var entries = {},
basename; glob.sync(globPath).forEach(function(entry) { basename = path.basename(entry, path.extname(entry));
entries[basename] = entry;
});
return entries;
} var pages = getEntry('src/pages/**/*.html'); for (var pathname in pages) {
var conf = {
filename: process.env.NODE_ENV === 'testing' ? pathname + '.html' : config.build[pathname],
template: pages[pathname],
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunks: [pathname]
}
plugins.push(new HtmlWebpackPlugin(conf));
} var webpackConfig = merge(baseWebpackConfig, {
module: {
rules: 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')
},
plugins: plugins
}) if (config.build.productionGzip) {
var CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push(newCompressionWebpackPlugin({asset:'[path].gz[query]',algorithm:'gzip',test:newRegExp('\\.('+
config.build.productionGzipExtensions.join('|')+')$'),threshold:10240,minRatio:0.8}))}if(config.build.bundleAnalyzerReport){varBundleAnalyzerPlugin=require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(newBundleAnalyzerPlugin())}module.exports = webpackConfig

好了,所有配置文件写完。

还有最后一步就是修改项目目录结构。

在src目录下新建一个page目录,然后建一个index目录用来放index.html、Index.vue、index_main.js三个文件。

如果有多个页面,就类似添加一个video目录存放三个文件,每个文件的书写方式。按照index文件书写方式一样。

index.html文件

<!DOCTYPE html>
<html> <head>
<meta charset="utf-8">
<link rel="shortcut icon" href="http://cdn.bunny-tech.com/promotion/static/act-imags/icon.png" />
<title>映兔视频</title>
</head> <body>
<div id="app"></div>
</body> </html>

Index.vue文件

<template>
<div class="warp">
<p>index</p>
<hello></hello>
</div>
</template>
<script>
import main from '../../lib/main'
import Hello from '../../components/Hello'
import store from '../../lib/store' export default {
name: 'index',
components: {
'hello': Hello
},
data() {
return {
bannerHref: '', }
},
mounted() {
this.loadData();
},
methods: {
loadData() {
var rep = {
bannerPosition: 'hasActive'
}
store.getinfo(rep,
function(res) {
if (res.errorCode == 0) {
console.log(res.data);
}
})
}
}
}
</script>
<style scoped>
.warp {
max-width: 750px;
margin: 0 auto;
background: #CCC;
}
</style>

index_main.js文件

import Vue from 'vue'
import App from './Index'
import Resource from 'vue-resource' Vue.use(Resource); new Vue({
el: '#app',
template: '<App/>',
components: { App }
})

ok了,记得删除主目录下的index.html文件哦,因为那个已经被我们移到page目录下面了。以后就安心写业务代码吧。不需要管配置的问题了。上面文件里关于vue-resource的代码,在写demo的时候都可以去掉,那是关于vue异步请求数据的,这个例子用不到。如果喜欢下次写一点关于vue异步请求数注意事项。