webpack入門

工做區設置

IDE

Visual Studio Codejavascript

插件

配置.vscode/settings.json

{
  "editor.tabSize": 2,

  "prettier.printWidth": 160,
  "prettier.tabWidth": 2,
  "prettier.semi": false,
  "prettier.singleQuote": true,

  "[vue]": {
    "editor.formatOnSave": true
  },
  "[javascript]": {
    "editor.formatOnSave": true
  },
  "[typescript]": {
    "editor.formatOnSave": true
  },
  "[stylus]": {
    "editor.formatOnSave": true
  },

  "stylusSupremacy.insertBraces": false,
  "stylusSupremacy.insertColons": false,
  "stylusSupremacy.insertSemicolons": false,

  "languageStylus.useSeparator": false,

  "vetur.format.defaultFormatterOptions": {
    "prettier": {
      "printWidth": 160,
      "tabWidth": 2,
      "semi": false,
      "singleQuote": true,
    }
  }
}

webpack項目配置和使用

安裝依賴的方式

安裝依賴的工具備2種npmyarn(推薦使用)css

依賴安裝的位置有全局安裝項目安裝:[例如安裝webpack]html

全局安裝npm install webpack -g or yarn global add webpackvue

項目安裝(推薦):java

開發依賴npm install webpack -D or yarn add webpack --devnode

​ 在生產時,所用到的依賴,不會加入到打包後的文件中。webpack

線上依賴npm install webpack or yarn add webpackes6

​ 會加入到打包後的文件中去。web

全局安裝項目安裝`的區別

全局安裝使用時,須要配置全局變量,而後直接webpack執行命令。
項目安裝使用時:
./node_modules/webpack/bin/webpack.js or
packge.json文件中配置scripts,執行scripts命令時,會直接去找當前根目錄下的node_modules下的依賴。typescript

起步

安裝依賴:yarn add webpack webpack-cli --dev`

webpack:打包工具

webpack-cliwebpack的必須依賴包

packge.json加入:

{
  "name": "webpack-test",
  "version": "1.0.0",
  "main": "main.js",
  "license": "MIT",
  "scripts": {
+   "build": "webpack"
  },
  "devDependencies": {
    "webpack": "^4.29.6",
    "webpack-cli": "^3.3.0"
  }
}

"build": "webpack":是爲了執行項目依賴webpack的時候,不須要使用./node_modules/webpack/bin/webpack.js這種方式執行項目,而能夠使用:yarn webpackor npm run webpack

新建、配置webpack.config.js文件

新建webpack.config.js,配置以下內容:

const path = require('path')

module.exports = {
  mode: 'production',
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'public'),
    filename: '[name].min.js'
  }
}

mode:提供 mode 配置選項,告知 webpack 使用相應模式的內置優化。

development:會將 process.env.NODE_ENV 的值設爲 development。啓用 NamedChunksPluginNamedModulesPlugin

能夠查看源碼,可是體積大

production:會將 process.env.NODE_ENV 的值設爲 production。啓用 FlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPluginUglifyJsPlugin

源碼沒法查看,可是體積小

entry:webpack的入口文件

output.path:輸入的路徑

output.filename:輸出文件名

​ [name] 延續以前js的命名

​ [hash] 使用hash值;解決緩存問題

打包相關的快捷插件

html-webpack-plugin

安裝:yarn add html-webpack-plugin --dev

添加html模板,並將動態的js文件添加到文件中,不須要手動添加js文件

clean-webpack-plugin

安裝:yarn add clean-webpack-plugin

清除output.path目錄下的全部文件

webpack.config.js中的配置入下:

plugins: [
    new Webpack.ProgressPlugin(),
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      title: 'Output Management'
    })
  ]

想要HtmlWebpackPlugin插件的title在html中生效,須要在index.html的title中添加<%= htmlWebpackPlugin.options.title %>以下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

在這裏使用yarn build,便可以打包出對應的文件。

若是是開發時,若是有開發的服務,是最好的。

使用webpack-dev-server開啓服務(devServer)

安裝:yarn add webpack-dev-server

webpack-dev-serverwebpack內置服務器;具體更多的webpack-dev-server配置項,查看官網

webpack.config.js中配置如下內容:

/**[webpackDev服務器]
   *  @contentBase            {服務器根目錄}
   *  @inline                 {true=正常模式;false=iframe模式}
   *  @hotOnly                {true禁用自動刷新}
   *  @historyApiFallback     {true=404時,使用index.html替代}
   *  @compress               {使用壓縮版本的js}
   *  @hot                    {使用熱更新}
   */
  devServer: {
    contentBase: './dist',
    compress: true,
    inline: true,
    hotOnly: false,
    hot: false,
    historyApiFallback: true
  },

packge.jsonscripts中加入"serve": "webpack-dev-server --open"

使用yarn serve既能夠開啓webpack服務器

--open 自動打開瀏覽器

到目前爲止,上線打包、開發的配置已經好了,那麼這就行了嗎?固然不是,若是是須要使用es6語法,固然是不支持的。

設置別名、自動解析綴名

resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    },
    extensions: ['.js']
  },

resolve設定解析規則

resolve.alias:設置別名

resolve.extensions:當沒有後綴名時,自動解析爲.js文件後綴。

支持ES6語法和代碼polyffil

安裝:yarn add babel-loader @babel/core @babel/preset-env @babel/plugin-syntax-dynamic-import --dev

babel-loader:webpack解析js文件的loader

@babel/preset-env:識別瀏覽器版本,對代碼polyfill到某個版本

@babel/core:執行代碼的polyfill

package.json的配置:

"browserslist": [
    "last 1 version",
    "> 1%",
    "maintained node versions",
    "not dead"
  ]

指定polyfill的最低版本.

webpack.config.js配置:

module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: ['@babel/preset-env'],
          /**默認狀況下,此插件將使用Babel的objectSpread幫助程序生成符合規範的代碼 */
          plugins: [require('@babel/plugin-proposal-object-rest-spread')]
        }
      }
    ]
  },

@babel/plugin-proposal-object-rest-spread:對象的解構

.js文件進行解析,並使用@babel/preset-env預置解析,使用@babel/plugin-transform-object-rest-spread插件。

引入reset.css重置樣式

yarn add @babel/plugin-syntax-dynamic-import --dev

@babel/plugin-syntax-dynamic-import:支持import()語法

src/main.js中加入:

import App from './pages/home/home.js'

import('@/asset/css/reset.css')

App()

重置樣式文件reset.css

body,h1,h2,h3,h4,h5,h6,hr,p,blockquote,dl,dt,dd,ul,ol,li,pre,form,fieldset,legend,button,input,textarea,th,td{margin:0;padding:0}
html{color:#000;overflow-y:scroll;overflow:-moz-scrollbars-vertical}
body,button,input,select,textarea{font-size:12px;font-family:arial,'Hiragino Sans GB','Microsoft Yahei','微軟雅黑','宋體',\5b8b\4f53,Tahoma,Arial,Helvetica,STHeiti}
h1,h2,h3,h4,h5,h6{font-size:100%}
em{font-style:normal}
small{font-size:12px}
ul,ol{list-style:none}
a{text-decoration:none}
a:hover{text-decoration:underline}
legend{color:#000}
fieldset,img{border:0}
button,input,select,textarea{font-size:100%}
table{border-collapse:collapse;border-spacing:0}
img{-ms-interpolation-mode:bicubic}
textarea{resize:vertical}
.left{float:left}
.right{float:right}
.overflow{overflow:hidden}
.hide{display:none}
.block{display:block}
.inline{display:inline}
.error{color:#F00;font-size:12px}
label,button{cursor:pointer}
.clearfix:after{content:'\20';display:block;height:0;clear:both}
.clearfix{zoom:1}.clear{clear:both;height:0;line-height:0;font-size:0;visibility:hidden;overflow:hidden}
.wordwrap{word-break:break-all;word-wrap:break-word}
pre.wordwrap{white-space:pre-wrap}
body,form{position:relative}
td{text-align:left}
img{border:0}

發現仍是報錯,由於沒有解析.css文件。

yarn add style-loader css-loader

style-loader:解析css

css-loader:將style樣式,插入行內樣式,webpack.config.js文件配置以下:

{
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      },

執行yarn serve,就能夠看到重置樣式了。

使用stylus書寫樣式

yarn add stylus stylus-loader --dev

安裝好依賴,在webpack.config.js中的module.rules配置以下:

{
        test: /\.styl$/,
        use: [
          'style-loader', 
          {
            loader: 'css-loader'
          },
          'stylus-loader'
        ]
      },

而後在就能夠使用stylus文件了。

熱更新

webpack.config.js中的devServerplugins中添加:

devServer: {
    contentBase: './dist',
    compress: true,
    hotOnly: false,
    hot: true,                  //新加
    historyApiFallback: true
  },

Webpack須要提早引入:

const Webpack = require('webpack')
plugins: [
    new Webpack.ProgressPlugin(),
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './public/index.html',
      title: 'Output Management'
    }),
    new Webpack.NamedModulesPlugin(),  //新加
    new Webpack.HotModuleReplacementPlugin()  //新加
  ]

在入口文件main.js中添加:

import App from './pages/home/home.js'

import('@/asset/css/reset.css')

import('./pages/home/index.styl')

//新加
if(module.hot){
  module.hot.accept(() => {
    App()
  })
}

App()

再次執行,便可實現熱更新。

解析.vue文件

yarn add vue-loader vue-template-compiler --dev

具體詳細文檔見vueLoader官網

webpack.config.js中配置:

module: {
    rules: [
      // ... 其它規則
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      }
    ]
  },
const VueLoaderPlugin = require('vue-loader/lib/plugin')
  
  ...
  plugins: [
    new VueLoaderPlugin()
  ]

main.js中加入:

import Vue from 'vue'
import App from '@/pages/App.vue'

import('@/asset/css/reset.css')

if(module.hot){
  module.hot.accept(() => {
    new Vue({
      render: function (h) {
        return h(App)
      }
    }).$mount('#app')
  })
}

new Vue({
  render: function (h) {
    return h(App)
  }
}).$mount('#app')

由於main.js不支持template模板解析語法,因此使用的函數渲染。

新增App.vue

<template lang="html">
  <div class="home">
    {{text}}
  </div>
</template>
<style lang="stylus" scoped>
.home
  color red
  font-size 18px
</style>
<script>
export default ({
  data () {
    return {
      text: 'Hello World'
    }
  },
})
</script>

這時候能夠運行成功了嘛?不可能.....還要對 .styl文件進行單獨處理:

yarn add stylus-loader --dev

以前已經裝過stylus,因此這裏就沒有裝。

配置webpack.config.js

module: {
    rules: [
        // 修改之以前匹配.styl規則
        {
            test: /\.styl(us)?$/,
            use: [
              'vue-style-loader', 
              'css-loader',
              'stylus-loader'
        ]
      },
    ]
}

而後就能夠在.vue文件中使用stylus

這裏有一個坑,test匹配規則必定要加:(us)?這句,不然會報錯。

使用pug文件開發

yarn add pug pug-plain-loader --dev

配置匹配規則:

module: {
    rules: [
      {
        test: /\.pug$/,
        loader: 'pug-plain-loader'
      },
   ]
 }

就能夠使用pug格式

相關文章
相關標籤/搜索