webpack4之vue组件渲染

493 阅读1分钟

这里只讲加载vue文件(组件)所需要注意的配置,其他自行配置或参考我之前的笔记

本练习项目打包后的目录结构

1 在终端执行命令

cnpm i vue-loader vue-template-compiler -D

package.json的配置如下

{
  "name": "webpack4-vue",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.config.js",
    "start": "webpack-dev-server --open"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^3.2.0",
    "vue-loader": "^15.7.1",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.39.2",
    "webpack-cli": "^3.3.7"
  },
  "dependencies": {
    "vue": "^2.6.10"
  }
}

2 在webpack.config.js中加入如下配置

Vue-loader在15.*之后的版本都是 vue-loader的使用都是需要伴生 VueLoaderPlugin的

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');

module.exports = {
	entry: {
		app: './src/main.js'
	},
	output: {
		filename: '[name].bundle.js',
		path: path.resolve(__dirname, 'dist')
	},
	devServer: {
		port: 3000,
		contentBase: './dist',
		progress: true
	},
	mode: 'development',

	plugins: [
		new HtmlWebpackPlugin({
			title: 'webpack-vue', // 生成的HTML文件的标题
			template: './src/index.html' // 使用的模板路径
		}),
		new VueLoaderPlugin()
	],

	module: {
		rules: [{
			test: /\.vue$/,
			use: [
				'vue-loader'
			]
		}]
	}

}

3 创建login.vue文件

<template>
	<div>
		<h1 @click="show()">这是登录组件------{{msg}}</h1>
	</div>
</template>

<script>
	export default{
		data(){
			return {
				msg:'hello world'
			};
		},
		methods:{
			show(){
				console.log("调用login.vue中的show()方法")
			}
		}
	}
</script>

<style>
</style>

一个模块只能有一个export default,但export 却不限制,都是用来向外暴露成员

4 在main.js中引入

import Vue from 'vue'
import login from './login.vue'

var vm=new Vue({
	el:'#app',
	data:{
		msg:123
	},
	render:function(createElements){
		return createElements(login)
	}
})

src/index代码如下

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
		</div>
	</body>
</html>

5 运行

在终端执行命令

cnpm run start

浏览器运行结果

个人网站:www.panbingwen.cn