Vue.js 学习笔记十一:Webpack之webpack 配置 配置使用 Vue

目录

配置使用 Vue

项目中使用

el 和 template 区别

Vue 组件化开发引入

.vue 文件封装处理


配置使用 Vue

后续项目中,我们会使用 Vue 进行开发,而且会以特殊的文件来组织 Vue 的组件。所以,下面我们来学习一下如何在我们的 webpack 环境中集成 Vue。

 

项目中使用

现在,我们希望在项目中使用 Vue,那么需要对其有依赖,所以需要先进行安装:

npm install vue --save

注:因为我们后续是在实际项目中也会使用 Vue 的,所以并不是开发时依赖。

index.js

import Vue from 'vue'
new Vue({
	el : '#app',
	data:{
		msg: 'hello vue'
	}
}) 

 index.html



	
		
		
	
	
		
{ { msg }}
html

接下来,打包运行发现没有显示出来,从控制台看到报错:

[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.
(found in )

意思是说:你正在使用 Vue 的仅运行时版本,但模板编译器不可用。 可以将模板预编译为渲染函数,也可以使用包含编译器的内部版本。

在 NPM 包的 dist/ 目录你将会找到很多不同的 Vue.js 构建版本。这里列出了它们之间的差别:

  UMD CommonJS ES Module (基于构建工具使用) ES Module (直接用于浏览器)
完整版 vue.js vue.common.js vue.esm.js vue.esm.browser.js
只包含运行时版 vue.runtime.js vue.runtime.common.js vue.runtime.esm.js -
完整版 (生产环境) vue.min.js - - vue.esm.browser.min.js
只包含运行时版 (生产环境) vue.runtime.min.js - - -
  • 完整版:同时包含编译器和运行时的版本。

  • 编译器:用来将模板字符串编译成为 JavaScript 渲染函数的代码。

  • 运行时:用来创建 Vue 实例、渲染并处理虚拟 DOM 等的代码。基本上就是除去编译器的其它一切。

  • UMD:UMD 版本可以通过

    但是,这种特殊的文件以及特殊的格式,必须有人帮助我们处理。这时使用 vue-loader 以及 vue-template-compiler

    安装 vue-loadervue-template-compiler

     npm install vue-loader vue-template-compiler --save-dev

    已安装过可以忽略。

    安装完成后可能会发现控制台有个警告:

    npm WARN [email protected] requires a peer of css-loader@ but none is installed. You must install peer dependencies you

    说明需要安装 css-loader 等相关依赖,否则无法正常打包。

    npm install style-loader css-loader --save-dev

     

    修改 webpack 的配置文件:

    const path = require('path')
    const {VueLoaderPlugin} = require('vue-loader')
    module.exports = {
    	entry: {
    		index : './src/index.js'
    	},
    	output: {
    	    path: path.resolve(__dirname, 'dist'),
    	    filename: '[name].js',
    	},
    	module: {
    		rules: [
    			{
    				test: /\.css$/, 
    				use: ['style-loader', 'css-loader'],
    			},
    			{
    				test: /\.vue$/,
    				use : 'vue-loader'
    			}
    		]
    	},
    	resolve: {
    		alias: {
    		  'vue$': 'vue/dist/vue.esm.js' 
    		}
    	},
    	plugins:[
    		new VueLoaderPlugin()
    	]
    	
    }

     

    Vue Loader v15 需要配合一个 webpack 插件才能正确使用:

    // webpack.config.js
    const { VueLoaderPlugin } = require('vue-loader')
    
    module.exports = {
    // ...
    plugins: [
     new VueLoaderPlugin()
    ]
    }

     

     

     

     

你可能感兴趣的:(Vue.js,学习笔记,vue,js,webpack)