Head First WEBPACK+VUE+Browser

Write on the front

This is pj's first blog for Recording my study line in detail.

I had the idea of writing a blog a long time ago, so the minute I done my project I can't wait to start writing.
For me,writing is always exciting,whatever poem or letter.
However,today I want to start my new journey in ENG I have ever try.
Why to write Technical Blog?One for myself to review and One for SHARE.

溫故而知新 順便打發(fā)時間

Foundation

Basic JS+CSS+HTML+npm
It also a task for me to share how I learn these,but not today.

GO

Project init

Take the first step

  • choose your file and init git Repo
    Here I use GitKraken
    init repo
  • cd and init project

npm init -y//init project -y means always yes

  • add .gitignore (this may usually foget but important for Engineering Simplicity(工程簡潔))
    .gitignore
  • Download modules
    First and foremost,download some vital modules
    npm install webpack webpack-cli -D //-D means save as dev
    npm install vue
    you would find that in package something appear

What is modules? I think it just like a machine in your project,it helps you product Components in your project.
CLI more like a machine-line(流水線)it Straightly give you everything.
But u may wonder What is Dependencies or devDependencies? Later we will discuss

but hey we may stop and think what we are doing and why???

Why we need webpack?

  • What we do before?
    Well if you go through the vue you may see this :
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    then you can use it in your this HTML, but just think about that when the project consists many pages.You may need to write a mass of shit in your every page.
  • So how to do?

When webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.
——From webpack.js.org

general speaking, it helps you pack your different components together so that you can Write different files according to requirements and use it when need , instead of write everything together.
It's art!
well but also magic.

  • Show some expamples
    if we want to use other things in html or js, we usually use script src='' in which we require or import some function or Variables , BUT, EXCEPT this file(.js .css .png) itself
    in this example,we need to make App importedf from .vue file to be a VUE object (well like the Vue.component() do ) but Obviously the browser does't work.
    require兑宇、import I need to read

    main.js

WEBPACK is the machine to make this work
SO,we can easily have a conclusion:

webpack not only solve the development issues in large page, but also a tool to help browser to import any file(by loader)

Expansion about what happen when browser read HTML

  • Async read:browser will read line by line and create dom tree at the same time

如果你在一個body里面的<script>標簽后面污秆,放一個<a id="xxx"> 那你在腳本里面骗爆,Document.getElementById("xxx")是獲取不到這個標簽的
——miigon

  • Difference:
    when the <style> is in index.html,then the browser will immediately create CSSOM and just line by line to read <head>and<body>
    when reading html tag it creates DOM tree but while script will stop whole HTML(but we have soluation)

.
image.png
here means all<link>load together

如果你直接寫在頁面里 那什么亂七八糟script執(zhí)行之前,就會先加載css了
——miigon

when using webpack, in a classic index.html like this:
<title>Todo應用</title></head><body><div id="app"></div><script src="bundle.js"></script></body>
as you see,there ain't <style> which would be dynamically generated when <script src="bundle.js"></script>runs.
There if we change the order <body><script src="bundle.js"></script><div id="app"></div></body> we will lose the page

So you can imagine that webpack is a magic(黑盒子) which make bundle.js can insert <style>or anything to the index.html

bundle.js的原理其實很簡單,里面就是,往dom里插入一堆<script> 和 <style>
——miigon
(此時,dom樹正在生成)

那么其實bundle.js差不多就相當于一個把各種阻塞資源都整合到一起了 并且放在頁面底部 要塞一起塞
但是bundle.js不僅會往這個html插入DOM和<style>標簽 還會有一堆script腳本, 而很多script是會導致阻塞的(假設bundle.js把console.log這句放在了<p/>前面 那么<p/>的解析是會被影響的) 不知道里面是根據(jù)什么順序去加載這些東西的

Conclusion question

  • The order borwser read and when and how to render tree
  • The principle(原理) of webpack and why we should use

Keep going

Time to start our webpack!

  • Configure
    now we have webpack,but not enough,because we doesn't use vue-cli so let's tell webpack what she should do
    new a file webpack.config.js in /newproject
// 使用node的path模塊
const path = require('path')

module.exports = {
  // 打包的入口
  entry: './main.js',
  // 打包的出口
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
    //__dirname指當前目錄 等價于__dirname + '/src'

  }
}

it tells webpack the basic command to get main.js and output a file 'bundle.js' to a Folder called'dist'
And then we could use bundle.js to add everthing to HTML!
so we try to import VUE.JS to main.js
New file main.js app.vue

//main.js
import App from './App.vue'
// 這個過程使用了loader 使App成為一個組件對象
import Vue from 'vue'
//從vue包導入vue對象 就像你在script里引入那樣

new Vue({// 創(chuàng)建Vue根實例 掛載到id為app的DOM上
  el: '#app',
  components:{
    //組件名:組件對象
    App:App//這個vue到這里才正式有了這個組件
  },
   template: '<App/>'//把掛載的DOM全部替換為我自己的組件
})
//App.vue
<template>
    <div>this is App</div>
</template>

<script type="text/javascript">
    export default {
        name: 'App'//注冊組件第一步 肯定要有名字
        //為什么這里就是注冊了呢 因為這些信息都會被import獲取 從而生成一個組件對象
    }
</script>

<style type="text/css"></style>
  • Not yet! wait for loader!
    If you carefully,you would find that we still try to make Browser import .vue
    Therefore,we use loader(loader is also a module like'vue' we installed) and tell webpack to use this
    npm install -D vue-loader css-loader style-loader file-loader stylus-loader
    and add rules to config:
  // 打包規(guī)則
  module: {
    rules: [
    {
      test: /\.vue$/,
      loader: 'vue-loader'
    },
    {
      test: /\.(jpg|jpeg|png|svg)$/,
      loader: 'file-loader',
      options: {
        name: '[name].[ext]'
      }
    },
    {
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    },
    {
      test: /\.styl(us)?$/,
      use: ['style-loader', 'css-loader', 'stylus-loader']
    },
    

    ]
  },

WOW now we can see a family!


  • Plugin
    we must use this to make sure vue can load correctly.I don't know why233


  • Scripts
    we should add some script to tell project start webpack or other things!


  • 萬事俱備
    Let's try! Build your first castle
    npm run build
    then we have a dist and a bundle.js!
    As long as we use it in script of HTML,we can see it in browser.

    index.html

    Don't forget the<div id='app'>!

  • well we have some bugs,let's find out:


See?We just import App first,but we don't have Vue to make it a component!(by the way don't Misspelled Words)
So we just make vue first as she want
What's more we should add alias in config!

好事多磨

  • Finally We Make It


  • Don't forget to commit to git whenever you want


    gitkraken

Conclusion of Init

  • webpack config:
    *output,entry,rules of module,plugins
  • components logic
    index.html as template(with the only one main <div>)
    => script of bundle.js(with whole sources)
    => main.js as entry with only one App.vue
    => App.vue as the collection of child.vues
  • comman bugs
    • module version conflict
    • component logic error

Start for real devlopment

  • File-Componentized construction
|-- src,
      |-- App.vue,
      |-- main.js,
      |-- assets,//assets for all source
      |   |-- images,
      |   |   |-- bg.jpg,
      |   |-- styles,
      |       |-- global.styl,
      |-- components,//for all components
          |-- MainFooter.vue,
          |-- MainHeader.vue,
          |-- MainTodo,
              |-- MainTodo.vue,
              |-- coms,
                  |-- TodoInfo.vue,
                  |-- TodoItem.vue,
//Remember to change your config when your file change
  • then you need to install these

HtmlWebpackPlugin (to make creat html with a template html(so we can use <div id='app'>)
CleanWebpackPlugin (to clean dist
webpack-dev-server it conflicts to webpack-cli@4 so we change to @3
webpack-merge

  • set your pubic(production) config
    • set your alias
resolve: {
      alias: {
        'vue': 'vue/dist/vue.js',
         '@': path.resolve(__dirname, '../src'),
    'styles': path.resolve(__dirname, '../src/assets/styles'),
    'images':path.resolve(__dirname,'../src/assets/images'),
      }
    },
  • Set your merge config
    using const {merge} = require('webpack-merge') in dev.js and prod.js and using module.exports = merge(baseConfig, prodConfig) mix together
  • Set your devlopment config
//in webpack.dev.js
//...require for plugins
const devConfig = {
  mode: 'development',
  devServer:{//Need to install
    contentBase:'./dist',
    open:true,
    hot:true
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()//from webpack itself
    ],
    devtool:'inline-source-map'//Find out your orginal error
  }
module.exports = merge(baseConfig, devConfig)
  • Reset the scripts to run
    "build": "webpack --config ./build/webpack.prod.js ", "dev": "webpack-dev-server --config ./build/webpack.dev.js"
  • npm run dev to try!

Conclusion of config

  • Important to think what is first like set .gitignore or resolve alias
  • Think and classify your file first
  • Using config merge to better differ different situation
  • Using path alias can not only for simple but also to lock your file path best
  • Think more about related config when some config changing

Componentized Development Thinking

  • CssPubicThinking
    Global Styles as a file
    Common Local Styles as a function in a file
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市鸟雏,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌览祖,老刑警劉巖孝鹊,帶你破解...
    沈念sama閱讀 221,888評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異展蒂,居然都是意外死亡又活,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,677評論 3 399
  • 文/潘曉璐 我一進店門锰悼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來柳骄,“玉大人,你說我怎么就攤上這事箕般∧褪恚” “怎么了?”我有些...
    開封第一講書人閱讀 168,386評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長曲初。 經(jīng)常有香客問我体谒,道長,這世上最難降的妖魔是什么复斥? 我笑而不...
    開封第一講書人閱讀 59,726評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮械媒,結果婚禮上目锭,老公的妹妹穿的比我還像新娘。我一直安慰自己纷捞,他們只是感情好痢虹,可當我...
    茶點故事閱讀 68,729評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著主儡,像睡著了一般奖唯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上糜值,一...
    開封第一講書人閱讀 52,337評論 1 310
  • 那天丰捷,我揣著相機與錄音,去河邊找鬼寂汇。 笑死病往,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的骄瓣。 我是一名探鬼主播停巷,決...
    沈念sama閱讀 40,902評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼榕栏!你這毒婦竟也來了畔勤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,807評論 0 276
  • 序言:老撾萬榮一對情侶失蹤扒磁,失蹤者是張志新(化名)和其女友劉穎庆揪,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體妨托,經(jīng)...
    沈念sama閱讀 46,349評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡嚷硫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,439評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了始鱼。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片仔掸。...
    茶點故事閱讀 40,567評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖医清,靈堂內(nèi)的尸體忽然破棺而出起暮,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 36,242評論 5 350
  • 正文 年R本政府宣布负懦,位于F島的核電站筒捺,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏纸厉。R本人自食惡果不足惜系吭,卻給世界環(huán)境...
    茶點故事閱讀 41,933評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望颗品。 院中可真熱鬧肯尺,春花似錦、人聲如沸躯枢。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,420評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽锄蹂。三九已至氓仲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間得糜,已是汗流浹背敬扛。 一陣腳步聲響...
    開封第一講書人閱讀 33,531評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留朝抖,地道東北人舔哪。 一個月前我還...
    沈念sama閱讀 48,995評論 3 377
  • 正文 我出身青樓,卻偏偏與公主長得像槽棍,于是被迫代替她去往敵國和親捉蚤。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,585評論 2 359

推薦閱讀更多精彩內(nèi)容