webpack使用總結 - ES六、模塊熱替換

接着上一篇文章中的配置css

一. Webpack Dev Server

在實際的開發中,不會每次改下代碼,而後再手動的打包、手動刷新頁面,這樣太麻煩了,webpack也是支持自動打包及刷新頁面的。html

webpack-dev-server能夠自動的打開頁面、自動的打包、自動的刷新、因此在項目中通常採起這種方式。node

安裝:yarn add webpack-dev-serverwebpack

在package.json中增長:git

"scripts": {
    "build": "webpack",
+ "dev": "webpack-dev-server"
}
複製代碼

webpack.config.js中添加:es6

module.exports = {
+ devServer: {
+ open: true // 自動打開頁面
+ }
}
複製代碼

頁面就是在本地的服務中打開,注意使用webpack-dev-server不會生成打包後的目錄,它將文件都放在內存中。github

還有一個比較經常使用的配置proxy,proxy能夠將你的請求進行代理,避免出現跨域問題。web

舉個例子:ajax

ajax.jsjson

const ajax = () => {
  const xhr = new XMLHttpRequest()
  const url = '/api/wikisecond/lemmasecond?lemmaId=10629668'
  xhr.open('get', url)
  xhr.onreadystatechange = function () {
    if(xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 304)) {
      console.log(JSON.parse(xhr.responseText))
    }
  }
  xhr.send()
}

export default ajax
複製代碼

index.js

+ import ajax from './ajax'
+ ajax()
複製代碼

webpack.config.js

devServer: {
    open: true,
    proxy: {
        '/api': {
            target: 'https://baike.baidu.com',
            changeOrigin: true,
            secure: false,
        }
    }
}
複製代碼

上面配置的意思就是將http://localhost:8080/api/xxxx代理到https://baike.baidu.com/api/xxx

從新打包結果:

直接拿到了百度百科的接口返回內容,沒有出現跨域。

二. 模塊熱替換

模塊熱替換的意思就是在不從新刷新頁面的狀況下,替換模塊,舉個例子:

addItem.js

import style from './style/index.scss'

export default function () {
  const button = document.createElement('button')
  button.textContent = 'add Item'
  button.onclick = () => {
    const item = document.createElement('p')
    item.textContent = 'item'
    item.classList.add(style.item)
    document.body.appendChild(item)
  }
  document.body.appendChild(button)
}
複製代碼

index.js

+ import addItem from './addItem'
+ addItem()
複製代碼

index.scss

.item {
  &:nth-of-type(odd) {
    background: pink;
  }
}
複製代碼

因爲以前配置了css-loader的modules致使css名很難辨認,這裏優化一下:

{
   loader: 'css-loader',
   options: {
       importLoaders: 2,
- modules: true
+ modules: {
+ localIdentName: '[name]_[local]_[hash:base64]'
+ }
   }
}
複製代碼

打包後:

每點擊一下add Item按鈕就會在頁面上增長一個item元素,奇數元素的背景色爲粉色。

若是這時候改一下背景色:

index.scss

.item {
   &:nth-of-type(odd) {
- background: pink;
+ background: orange;
   }
 }
複製代碼

頁面會從新刷新,那麼以前添加的item就都沒了。

又得去點擊add Item按鈕才行,若是想保持以前的頁面狀態,那麼就要用到模塊熱替換功能:

wenpack.config.js

+ const webpack = require('webpack')

devServer: {
    open: true,
    proxy: {
      '/api': {
        target: 'https://baike.baidu.com',
        changeOrigin: true,
        secure: false,
      }
    },
+ hot: true,
+ hotOnly: true
},
plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve('template', 'index.html')
    }),
    new CleanWebpackPlugin(),
+ new webpack.HotModuleReplacementPlugin()
]
複製代碼

hot就是開啓模塊熱替換,hotOnly是告訴webpack在模塊熱替換失敗的時候不要從新刷新頁面。

可是關於js代碼的熱更新就有點麻煩,得這樣寫:

index.js

if (module.hot) {
    module.hot.accept('變更的模塊路徑', function () {
      // 作一些事情
    })
}
複製代碼

三. 處理ES6語法

雖然ES6在很早就發佈了,可是仍是有瀏覽器沒有實現ES6中的部分語法,因此須要對ES6的語法進行降級,要用到的就是babel了。

找到官方推薦配置,webpack

  1. 安裝相關包

    yarn add babel-loader @babel/core @babel/preset-env -D
    複製代碼
  2. webpack.config.js中添加

    module: {
        rules: [
    + { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }
        ]
    }
    複製代碼
  3. 建立.babelrc文件:

    {
        "presets": ["@babel/preset-env"]
    }
    複製代碼
  4. 測試一下:

    es6-test.js

    export default async () => {
        await new Promise(resolve => {
            setTimeout(() => {
                console.log('step 1')
                resolve()
            }, 1000)
        })
        console.log('step 2')
    }
    複製代碼

    index.js

    import es6Test from './es6-test'
    es6Test()
    複製代碼

    打包後:

    爲什麼按照官網的配置也會出錯!!!

    搜索了一下,發現了新世界,babel竟然也這麼難配置?看了不少教程,我以爲這個寫的最好Babel快速上手使用指南,那麼就按照這篇來配置:

    yarn add @babel/plugin-transform-runtime -D

    yarn add @babel/runtime core-js@3

    .babelrc

    {
         "presets": [
             ["@babel/preset-env", {
                 "modules": false,
                 "useBuiltIns": "usage",
                 "corejs": 3
             }]
         ],
         "plugins": ["@babel/plugin-transform-runtime"]
     }
    複製代碼

    從新打包,終於能夠了。

    開發模式打包的大小:

    正式模式打包的大小:

完整的配置:GitHub

相關文章
相關標籤/搜索