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.

温故而知新 顺便打发时间

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执行之前,就会先加载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/>的解析是会被影响的) 不知道里面是根据什么顺序去加载这些东西的

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({// 创建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:
  // 打包规则
  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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容