环境介绍css
系统:macOSHigh Sierra 10.13
node版本:v8.4.0
npm版本:5.3.0html
搭建过程vue
npm init
,输入必要的信息npm install webpack --save-dev
(注:可采用淘宝源,能够安装一个nrm工具,这个工具可用于切换npm包的获取地址,具体非本文主要内容)npm install --save-dev path
安装path以备使用在项目目录下新建一个文件,webpack.config.js
,内容代码以下,官网直接拿过来的node
var path = require('path'); module.exports = { entry: './app/index.js', output: { filename: 'index.js', path: path.resolve(__dirname, 'dist') } };
有了上面这些,按照官网就能够来进行编译了,具体请查看官网,那么如何来进行vue项目的构建呢,请继续往下看。webpack
*.vue
文件,咱们还须要vue-template-compiler
,还须要vue-loader
来加载vue安装完成以后,新建目录结构如图git
其中,代码以下Examples.vue
github
<template> <p>Hello,{{name}}</p> </template> <script> export default { name: 'Examples', data: function() { return { name: 'jackwang' } } }; </script>
index.js
web
import Vue from 'vue'; import Examples from './template/Examples.vue'; new Vue({ el: '#app', components: { 'Examples': Examples } });
index.html
npm
<body id="app"> <examples></examples> <script src="../dist/index.js"></script> </body>
而后进行项目[请见github示例]编译,打开浏览器,发现控制台,报了以下错误json
[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 <Root>)
看npm包中的vue的package.json
能够知道,main的指向dist/vue.runtime.common.js
为了解决这个问题,只要咱们在webpack.config.js
中加上这个便可
resolve: { alias: { vue: 'vue/dist/vue.js' // 注意此处为坑 } }
此时在再加载页面发现
[Vue warn]: Do not mount Vue to <html> or <body> - mount to normal
elements instead.
实际上是vue不容许在body上操做,于是我将id="app"放到了div上,此时一个vue项目基本搭建完成
有些朋友可能很喜欢css in js
,当你写某些组件时,将css放在组件当中,它的可移植性很是高,示例以下,在Examples.vue
中添加
<style> p{color: red;} </style>
可是仅仅这样没法进行成功编译的,咱们还须要loader来对这些样式进行编译,咱们须要style-loader将style标签注入到页面当中,同时须要css-loader
来加提取css,npm install --save-dev style-loader
并在webpack.config.js
中module
中rules
添加规则,css-loader同理,(注:use中是从右到左执行)
{test: /\.css/, use: 'style-loader!css-loader'}
此时再编译便可,为了便于使用,能够再package.json
中添加build命令,则能够用npm run build
来进行编译,以下,将build写在这个位置
"scripts": { "build": "webpack --watch", // 就是这句,这样能够热更新 "test": "echo \"Error: no test specified\" && exit 1" //这句是默认的,不用管 }
12.看起来是完了,是若是要引入一张背景图片呢,看看会出现什么问题,发现编译不经过,因此须要url-loader
来进行url解析,同理10的安装方法,效果再一次实现
结语
若是再遇到什么报错,请看是否是还须要什么loader,利用webpack搭建vue基本就说到这了,示例地址:https://github.com/IhInspirat...,写的若有错误或不完整之处,请评论交流,谢谢 !