如何利用webpack搭建vue環境

環境介紹css

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

搭建過程vue

  1. 新建一個新的文件夾,進入文件夾,命令行中npm init,輸入必要的信息
  2. 安裝webpack npm install webpack --save-dev(注:可採用淘寶源,能夠安裝一個nrm工具,這個工具可用於切換npm包的獲取地址,具體非本文主要內容)
  3. 利用npm install --save-dev path安裝path以備使用
  4. 在項目目錄下新建一個文件,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

  5. 首先要安裝vue爲了編譯*.vue文件,咱們還須要vue-template-compiler,還須要vue-loader來加載vue
  6. 安裝完成以後,新建目錄結構如圖
    圖片描述git

    其中,代碼以下
    Examples.vuegithub

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

    index.jsweb

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

    index.htmlnpm

    <body id="app">
        <examples></examples>
        <script src="../dist/index.js"></script>
    </body>
  7. 而後進行項目[請見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' // 注意此處爲坑
        }
    }
  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...,寫的若有錯誤或不完整之處,請評論交流,謝謝 !

相關文章
相關標籤/搜索