Vue(day6)

一、webpack中常用的文件loader & 插件

由于版本存在变动,以下安装和配置都有可能发生变化,请以官方文档为准。

1、html-webpack-plugin插件

html-webpack-plugin是在内存中生成html模板的插件plugin

首先安装插件npm install html-webpack-plugin -D,然后在配置文件webpack.config.js中进行插件配置:

const HtmlWebpackPlugin = require('html-webpack-plugin');
//....
plugins: [
    //注意:模板地址未找到会报错
    new htmlWebpackTemplate({
        template: path.join(__dirname, "/src/index.html"),
        filename: 'index.html'
    })
]

2、css的loader:style-loader&css-loader

同样的先安装loader模块:

npm install style-loader css-loader -D

然后在配置文件中进行模块向配置:

module: {
    rules: [
        {test: /.css$/, use: ['style-loader', 'css-loader']},//注意顺序不能错,从后往前调用
    ]
}

3、less loader:less-loader;scss loader:sass-loader

同时一样的配置方法。类似的非js文件都需要我们手动去配置对应的文件加载loader。

4、url loader:url-loadr&file-loader

有时候我们需要在css中引用图片等文件作为背景,这个时候涉及到url的解析,以及文件的加载,所以需要url和file的loader。

安装后基本配置:

//file-loader是url-loader的内部依赖,所以配置url-loader即可。
{test: /.(jpg|png|bmp|jpeg|gif)$/, use: 'url-loader'}

注意

  • 加载资源时默认加载为base64字节形式,但可以在配置中进行限制:

    {test: /.(jpg|png|bmp|jpeg|gif)$/, use: 'url-loader?limit=2048name=[name].[ext]'}
    //使用limit参数来限制字节数,大于或等于limit值时不转为base64字符。
    //name参数是保留文件名和后缀。但是这样在引入不同目录的同名文件时先引入的文件会被覆盖。
    //可以设置hash值进行区别:url-loader?limit=2048&name=[hash:8][name].[ext]
    
  • 使用字体图标时同样需要使用url-loader

    比如我们使用bootstrap中的字体图标(注意安装的时候请安装3.x.x的版本,4的版本不带字体图标)。

    我们可以直接在index.js中使用,首先引用css文件,然后再随便使用一个字体图标即可看到效果。

    字体loader配置:

    {test: /.(ttf|svg|eot|woff|woff2)$/, use: 'url-loader'}
    

    我们可以在页面中这样使用:

    <!--引入css-->
    <link rel="stylesheet" type="text/css" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
    
    <!--使用字体图标-->
    <span class="glyphicon glyphicon-music" aria-hidden="true"></span>
    

    既然我们使用了webpack,就不推荐这样直接在页面引入的形式,我们应该在入口文件main.css中引入这个bootstrap.css文件,像这样:

    //注意:对于导入node_modules下面的文件可省略前面的路径
    import 'bootstrap/dist/css/bootstrap.min.css';
    

5、babel模块的使用

有时候我们希望使用最新es6语法进行项目开发,但是webpack可能还没有最好支持的时候,我们就可以安装配置babel相关的模块进行js文件的解析加载。

如果在webpack中某些es6es7的高级语法号无法直接使用时,还需要使用一些loader来处理这些高级语法。

  • 安装需要的模块:
npm install babel-core babel-loader babel-plugin-transform-runtime -D
npm install babel-preset-env babel-preset-stage-0 -D

说明babel-preset-env babel-preset-stage-0为babel需要的语法模块;另外的为需要的语法转换器模块

  • 然后进行配置:
{test: /.js$/, use: 'babel-loader', exclude:/node_modules/}
//配置 babel 规则时必须把 node_modules 目录排除,如果不排除会把目录下的js文件都打包,这样会非常消耗cpu。
  • .babelrc配置文件

在项目根目录新建.babelrc配置文件,必须符合json格式规范。(不能注释;字符串必须使用双引号等)

配置项:

{
    "presets": ["env", "stage-0"],
    "plugins": ["transform-runtime"]
}

注意不需要插件或语法的前缀。

更多细节请参考:https://webpack.docschina.org/loaders/babel-loader/#src/components/Sidebar/Sidebar.jsx

二、在webpack中使用vue

在使用之前我们先安装Vue:

npm install vue -D

1、组件的使用:使用模板形式

先回顾一下组件的使用:

//创建一个组件模板
var buttonCounter = {
    data: function(){
        return {
            count: 0,
        }
    },
    template: '<a @click="++count">you click me {{count}} times!</a>'
}
//全局注册
Vue.component('button-counter', buttonCounter);
//局部注册
new Vue({
	el: '#app',
	components:{
		'button-counter': buttonCounter,
	}
});
<!--组件接口-->
<button-counter></button-counter>

我们先尝试直接拿到webpack环境下使用看看能否直接使用:

//导入vue模块
import Vue from 'vue';

//创建一个组件模板
var buttonCounter = {
    data: function(){
        return {
            count: 0,
        }
    },
    template: '<button @click="++count">you click me {{count}} times!</button>'
}

//注册到Vue实例中
new Vue({
	el: '#app',
	components:{
		'button-counter': buttonCounter,
	}
});

访问页面发现运行报错:

vue.runtime.esm.js:620 [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

报错的原因是vue在node中引用的这个js文件是runtime-only运行时环境包,功能并没有原来页面中所引用的全面,这个包无法直接渲染组件到页面中。

我们可以手动更改引入的包:

import Vue from 'vue/dist/vue.js'

这样再运行就不会报错了。

2、组件的使用:使用函数渲染形式

除了使用component挂在的方式,还可以使用render函数进行渲染,但是两者渲染有所区别:

new Vue({
    el: '#app',
    render: function(createElement){
    	return createElement(html)
    }
});

3、单文件组件的使用

既然Vue默认使用了运行时环境的包,就是希望我们使用这个包进行开发而不是手动去引用完整包。

运行时的模块无法直接渲染,但是可以使用render函数配合单文件组件来使用。

注意,render函数会将实例的已有内容清空再渲染,所以如果使用了render函数进行页面渲染,实例根元素内部的元素都没有必要再书写了。

但是如果我们的实例内部元素都写在组件注册中,无疑太冗杂,所以我们需要使用单文件组件进行开发。

文件扩展名为 .vuesingle-file components(单文件组件) 解决了Vue.component定义组件存在的相关局限,并且还可以使用 webpack 或 Browserify 等构建工具,也更符合模块式编程的思想。

由于引用的为.vue格式的文件,自然需要安装配置相应的loader:

npm install vue-loader vue-template-compiler -D
{test: /.vue$/, use: 'vue-loader'}

此外,还需要确保在你的 webpack 配置中添加 Vue Loader 的插件(必须):

const VueLoaderPlugin = require('vue-loader/lib/plugin')

//...
plugins: [
    new VueLoaderPlugin()
]

这样,我们就可以直接把.vue格式的文件引入作为render的模板文件。

书写一个类似这样的单文件组件:由三部分组成,

<template>
  <div class="example">
    {{msg}}
  </div>
</template>

<script>
export default {
  data () {
    return {
      msg: 'Hello world!'
    }
  }
}
</script>

<style>
.example {
  color: red;
}
</style>

可以发现, 单文件组件比普通的组件注册多了css控制。

参考地址:

单文件组件规范

Vue-loader

4、export 和 export default的区别

值得注意的是,module.exports导出模块接口的方法是Node提供的,符合commonJS规范,导入模块时使用的是require()方法。

es6对于模块的两个关键字,importexport,同样可以使用require关键字进行模块的导入。

[总结一下]

require: node 和 es6 都支持的引入
export / import : 只有es6 支持的导出引入
module.exports / exports: 只有 node 支持的导出

参考:

https://www.cnblogs.com/fayin/p/6831071.html

https://segmentfault.com/a/1190000010426778

5、结合使用vue-router,子路由和抽离路由

  • 复习Vue-Router的使用

    使用之前记得安装:

    npm install vue-router -D
    

    js代码:

    import VueRouter from 'vue-router';
    
    //1、创建路由视图组件
    var home = {template: '<h3>This is home page!</h3>'};
    var about = {template: '<h3>This is about page!</h3>'};
    //2、创建路由规则
    var routes = [
        {path: '/home', component: home},
        {path: '/about', component: about}
    ];
    //3、创建一个路由实例
    var router  = new VueRouter({
        routes: routes
    });
    //4、将路由搭载到Vue实例中
    new Vue({
        el: '#app',
        router: router
    });
    
  • webpack中使用:

    需要注意两个区别,我们需要手动挂载到Vue上,使用use方法:

    Vue.use(VueRouter)//手动挂载路由
    

还有就是路由的视图组件不能直接这样写,需要使用单文件组件来定义视图组件,否则回报runtime-only...错误。

6、Vue 中style的lang属性 和 scoped属性

lang属性可以指定样式使用的语言,比如lessscss等。

scoped属性存在时style的作用域就只在当前组件,否则为全局样式。

原文地址:https://www.cnblogs.com/fzz9/p/10679368.html