如何利用webpack搭建vue环境

环境介绍

系统:macOSHigh Sierra 10.13
node版本:v8.4.0
npm版本:5.3.0

搭建过程

  1. 新建一个新的文件夹,进入文件夹,命令行中npm init,输入必要的信息
  2. 安装webpack npm install webpack --save-dev(注:可采用淘宝源,可以安装一个nrm工具,这个工具可用于切换npm包的获取地址,具体非本文主要内容)
  3. 利用npm install --save-dev path安装path以备使用
  4. 在项目目录下新建一个文件,webpack.config.js,内容代码如下,官网直接拿过来的

        var path = require('path');
        module.exports = {
            entry: './app/index.js',
                output: {
                filename: 'index.js',
                path: path.resolve(__dirname, 'dist')
            }
        };

    有了上面这些,按照官网就可以来进行编译了,具体请查看官网,那么如何来进行vue项目的构建呢,请继续往下看。

  5. 首先要安装vue为了编译*.vue文件,我们还需要vue-template-compiler,还需要vue-loader来加载vue
  6. 安装完成之后,新建目录结构如图
    《如何利用webpack搭建vue环境》

    其中,代码如下
    Examples.vue

    <template>
        <p>Hello,{{name}}</p>
    </template>
    
    <script>
        export default {
            name: 'Examples',
            data: function() {
                return {
                    name: 'jackwang'
                }
            }
        };
    </script>

    index.js

    import Vue from 'vue';
    import Examples from './template/Examples.vue';
    
    new Vue({
        el: '#app',
        components: {
            'Examples': Examples
        }
    });

    index.html

    <body id="app">
        <examples></examples>
        <script src="../dist/index.js"></script>
    </body>
  7. 然后进行项目[请见github示例]编译,打开浏览器,发现控制台,报了如下错误

    [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' // 注意此处为坑
        }
    }
  8. 此时在再加载页面发现

    [Vue warn]: Do not mount Vue to <html> or <body> – mount to normal
    elements instead.

    其实是vue不允许在body上操作,因而我将id=”app”放到了div上,此时一个vue项目基本搭建完成

  9. 有些朋友可能很喜欢css in js,当你写某些组件时,将css放在组件当中,它的可移植性非常高,示例如下,在Examples.vue中添加

    <style>
        p{color: red;}
    </style>
  10. 但是仅仅这样无法进行成功编译的,我们还需要loader来对这些样式进行编译,我们需要style-loader将style标签注入到页面当中,同时需要css-loader来加提取css,npm install --save-dev style-loader并在webpack.config.jsmodulerules添加规则,css-loader同理,(注:use中是从右到左执行)

    {test: /\.css/, use: 'style-loader!css-loader'}
  11. 此时再编译即可,为了便于使用,可以再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…,写的如有错误或不完整之处,请评论交流,谢谢 !

    原文作者:jackwang
    原文地址: https://segmentfault.com/a/1190000011964664
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞