安装vue

1. 全局安装 vue-cli环境
npm install --global vue-cli
2. 创建一个基于webpack模板的新项目
vue init webpack my-project //项目名
3. 随着选择项配置你想要的项目
4. cd my-project
5. npm run dev

sass 安装使用

1.安装 必须安装node-sass环境
npm install node-sass sass-loader style-loader -D
2.使用
build/webpack.base.conf.js
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
3. 报错
Module build failed: TypeError: this.getResolve is not a function
at Object.loader (/Users/mac/new-project/redpacket/node_modules/sass-loader/dist/index.js:52:26)
4. 原因
sass-loader 版本过高,不兼容webpack, 降低版本到7.0.0
5. 重新 npm i
6. vue tempalte 下:
<style lang="scss" scoped type="text/scss">
@import './style.scss'; //或者单独的文件
</style>

配置

1. 删除
删除src 下的APP.vue 和 main.js router文件夹
2. 在src 下新建文件夹 pages/redpacket
3. redpacket文件夹下,新建redpacket.html,style.scss, redpacket.js; 这是入口文件
4. redpacket文件夹下, 新建component 这是组件; 新建router文件夹,这是当前单页面的router文件
5. redpacket.html 内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0"/>
</head>
<body>
<div id="app">
<div class="common-warp">
<router-view></router-view>
</div>
</div>
</body>
</html>
6. redpacket.js 内容
import Vue from 'vue';
import router from './router/index';
import './style.scss'; new Vue({
el: '#app',
router
}); 7. component
新建一个main.vue 里面是你的真实内容
<template>
<div class="redpacket-page">
<div class="content">内容</div>
</div> </template> <script>
export default {
name: "redpacket"
}
</script> 8. router 是router文件
import Vue from 'vue'
import Router from 'vue-router' Vue.use(Router); //首页
const Index_Redpacket = resolve => {
require.ensure([], () => {
resolve(require('../component/main.vue'));
}, 'main');
}; export default new Router({
routes: [
{
path: '/',
component: Index_Redpacket,
},
]
}) 7. build文件夹下修改
/////////--build/utils.js--///// start //////////////////////////////
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const packageConfig = require('../package.json') =====================配置入口文件和输入形式,并且一并export出去=================
var glob = require('glob');
//页面模板
var HtmlWebpackPlugin = require('html-webpack-plugin');
//获取路径
var PAGE_PATH = path.resolve(__dirname, '../src/pages');
//merge处理
var merge = require('webpack-merge'); //多入口配置
// 通过glob模块读取pages文件夹下的所有对应文件夹下的js后缀文件,如果该文件存在 文件名和js命名一致,但是只有一个入口文件, 那么就作为入口处理
exports.entries = function() {
var entryFiles = glob.sync(PAGE_PATH + '/*/*.js')
var map = {}
entryFiles.forEach((filePath) => {
var filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
map[filename] = filePath
})
return map
} //多页面输出配置
// 与上面的多页面入口配置相同,读取pages文件夹下的对应的html后缀文件,然后放入数组中
exports.htmlPlugin = function() {
let entryHtml = glob.sync(PAGE_PATH + '/*/*.html')
let arr = []
entryHtml.forEach((filePath) => {
let filename = filePath.substring(filePath.lastIndexOf('\/') + 1, filePath.lastIndexOf('.'))
let conf = {
// 模板来源
template: filePath,
// 文件名称
filename: filename + '.html',
// 页面模板需要加对应的js脚本,如果不加这行则每个页面都会引入所有的js脚本
chunks: ['manifest', 'vendor', filename],
inject: true
}
if (process.env.NODE_ENV === 'production') {
conf = merge(conf, {
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
},
chunksSortMode: 'dependency'
})
}
arr.push(new HtmlWebpackPlugin(conf))
})
return arr
} ===============utils.js 配置结束======================= exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path)
} exports.cssLoaders = function (options) {
options = options || {} const cssLoader = {
loader: 'css-loader',
options: {
sourceMap: options.sourceMap
}
} const postcssLoader = {
loader: 'postcss-loader',
options: {
sourceMap: options.sourceMap
}
} // generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] if (loader) {
loaders.push({
loader: loader + '-loader',
options: Object.assign({}, loaderOptions, {
sourceMap: options.sourceMap
})
})
} // Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
} // https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
} // Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
const output = []
const loaders = exports.cssLoaders(options) for (const extension in loaders) {
const loader = loaders[extension]
output.push({
test: new RegExp('\\.' + extension + '$'),
use: loader
})
} return output
} exports.createNotifierCallback = () => {
const notifier = require('node-notifier') return (severity, errors) => {
if (severity !== 'error') return const error = errors[0]
const filename = error.file && error.file.split('!').pop() notifier.notify({
title: packageConfig.name,
message: severity + ': ' + error.name,
subtitle: filename || '',
icon: path.join(__dirname, 'logo.png')
})
}
} /////////--build/utils.js--///// end ////////////////////////////// /////////--build/webpack.base.conf.js--/////start//////////////////////////////
module.exports = {
entry: utils.entries(),
}
/////////--build/webpack.base.conf.js--///// end ////////////////////////////// /////////--build/webpack.dev.conf.js--/////start//////////////////////////////
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-plugin
=============删除这段=======================
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
===============删除这段=====================
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.dev.assetsSubDirectory,
ignore: ['.*']
}
])
].concat(utils.htmlPlugin()) =======concat添加出口文件配置 /////////--build/webpack.dev.conf.js--///// end ////////////////////////////// /////////--build/webpack.prod.conf.js--///// start //////////////////////////////
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// 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 }
}),
// 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: config.build.index,
template: 'index.html',
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'
}),
=================修改 注释或者删除,随你===============================
// keep module.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// 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',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}), // copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])
].concat(utils.htmlPlugin()) ===== 修改
/////////--build/webpack.prod.conf.js--///// end //////////////////////////////

配置结束

重新打包dist文件夹 可以了

说明

这样可以把每个页面都当成当页面来用,想添加一个页面,在src下再建一个即可。并且当页面内部,router是独立的,比较方便管理。当然一些公用的方法,可以在pages文件夹同级目录下建立。

配置vue 多页面的更多相关文章

  1. 在webpack中配置.vue组件页面的解析

    1. 运行`cnpm i vue -S`将vue安装为运行依赖: 2. 运行`cnpm i vue-loader vue-template-compiler -D`将解析转换vue的包安装为开发依赖: ...

  2. VUE 多页面配置(二)

    1. 概述 1.1 说明 项目开发过程中会遇到需要多个主页展示情况,故在vue单页面的基础上进行配置多页面开发以满足此需求,此记录为统一配置出入口. 2. 实例 2.1 页面配置 使用vue脚手架搭建 ...

  3. VUE 多页面配置(一)

    1. 概述 1.1 说明 项目开发过程中会遇到需要多个主页展示情况,故在vue单页面的基础上进行配置多页面开发以满足此需求. 2. 实例 2.1 页面配置 2.1.1 默认首页 使用vue脚手架搭建后 ...

  4. VUE 多页面打包webpack配置

      思路:多配置一个main的文件,用于webpack入口使用, 然后路由的导向也应该默认指向新组件,最后通过webpack构建出一个新的独立的html文件. 缺点:生成多个html会new出多个vu ...

  5. Vue单页面骨架屏实践

    github 地址: VV-UI/VV-UI 演示地址: vv-ui 文档地址:skeleton 关于骨架屏介绍 骨架屏的作用主要是在网络请求较慢时,提供基础占位,当数据加载完成,恢复数据展示.这样给 ...

  6. vue单页面打包文件大?首次加载慢?按需加载?是你打开方式不对

    部署各vue项目,走了一遍坑.... vue单页面应用刷新404 找到nginx多网站配置文件:类似nginx/sites-available/www.baidu.com server { liste ...

  7. WebStorm配置Vue开发环境

    虽然最新版的前端开发利器WebStorm支持了Vue,但是大部分人的WebStorm依然是默认不支持Vue的老版本(比如之前的我),所以需要手动添加WebStorm对Vue的支持.要想让WebStor ...

  8. [转] 2017-11-20 发布 另辟蹊径:vue单页面,多路由,前进刷新,后退不刷新

    目的:vue-cli构建的vue单页面应用,某些特定的页面,实现前进刷新,后退不刷新,类似app般的用户体验.注: 此处的刷新特指当进入此页面时,触发ajax请求,向服务器获取数据.不刷新特指当进入此 ...

  9. 另辟蹊径:vue单页面,多路由,前进刷新,后退不刷新

    目的:vue-cli构建的vue单页面应用,某些特定的页面,实现前进刷新,后退不刷新,类似app般的用户体验.注: 此处的刷新特指当进入此页面时,触发ajax请求,向服务器获取数据.不刷新特指当进入此 ...

随机推荐

  1. React拾遗(上)

    JSX代表Objects Babel转义器会把JSX转换成一个名为React.createElement()的方法调用. 下面两种代码的作用是完全相同的: const element = ( < ...

  2. Golang基础笔记

    <基础> Go语言中的3个关键字用于标准的错误处理流程: defer,panic,recover. 定义一个名为f 的匿名函数: Go 不支持继承和重载. Go的goroutine概念:使 ...

  3. python小白之np功能快速查

    np一些用法 np.a np.array([1,2,3],dtype=int)  #建立一个一维数组, np.array([[1,2,3],[2,3,4]])  #建立一个二维数组. np.arang ...

  4. Facebook libra开发者文档- 2 -Libra Protocol: Key Concepts核心概念

    Libra Protocol: Key Concepts https://developers.libra.org/docs/libra-protocol Libra区块链是一个加密认证的分布式数据库 ...

  5. Jmeter与BlazeMeter使用 录制导出jmx

    本文链接:https://blog.csdn.net/weixin_38250126/article/details/82629876JMeter 的脚本录制,除了自带的HTTP代理服务器以外,被大家 ...

  6. Spring MVC Action参数类型 List集合类型(简单案例)

    题目:定义一个员工实体(Employee),实现批量添加员工功能,在表单中可以一次添加多个员工,数据可以不持久化 1,新建一个项目 2, 然后选择Maven框架选择 maven-archetype-w ...

  7. 【425】堆排序方法(二叉堆)优先队列(PQ)

    参考:漫画:什么是二叉堆? 大根堆 小根堆 参考:漫画:什么是堆排序? 参考:漫画:什么是优先队列? 参考:[video]视频--第14周10--第8章排序10--8.4选择排序3--堆排序2--堆调 ...

  8. Day7作业:选课系统

    这周的作业有点糙,迁就看吧,给大家点思路: readme: 需要安装模块: prettytable 测试帐号: 1.后台管理:admin/admin 只设定了这个后台管理帐号,没有写到数据库中 2.学 ...

  9. c# 调用mysql数据库验证用户名和密码

    使用mysql数据库验证用户名和密码时,如果用户名是中文,一直查不到数据 需要把app.config 中修改为 数据库统一设置utf8编码格式,连接数据库的时候设置编码Charset=utf8可以避免 ...

  10. LeetCode_21. Merge Two Sorted Lists

    21. Merge Two Sorted Lists Easy Merge two sorted linked lists and return it as a new list. The new l ...