webpack學習之路(四)

開發:

  ps:本指南中的工具僅用於開發環境,請不要在生產環境中使用。css

  先設置一下模式:html

webpack.config.jsnode

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
  const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
+   mode: 'development',
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    devtool: 'inline-source-map',
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Development'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

使用source-map:

  使用webpack打包資源後,追蹤到錯誤和警告在源代碼中的位置有時候會變得比較困難。好比你把a.js、b.js、c.js打包成了bundle.js,若是某個源文件報錯了,那堆棧跟蹤只會指向bundle.js。爲了更好地追蹤錯誤和警告,js提供了source maps,會把編譯後的代碼映射回源代碼,以以上例子爲例,若是a.js報錯了source maps就會準確地告訴你是它報錯了。source maps有不少的選項可用,最好仔細地閱讀一下這些配置以便按需配置。本指南里咱們使用inline-source-map選項(出於更好地解釋說明的目的,不要用於生產環境)。webpack

webpack.config.jsweb

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
  const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
+   devtool: 'inline-source-map',
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Development'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

  在print.js中造一個錯誤:express

src/print.jsnpm

  export default function printMe() {
-   console.log('I get called from print.js!');
+   cosnole.error('I get called from print.js!');
  }

  跑起來:json

Hash: 7bf68ca15f1f2690e2d1
Version: webpack 3.1.0
Time: 1224ms
          Asset       Size  Chunks                    Chunk Names
  app.bundle.js    1.44 MB    0, 1  [emitted]  [big]  app
print.bundle.js    6.43 kB       1  [emitted]         print
     index.html  248 bytes          [emitted]
   [0] ./src/print.js 84 bytes {0} {1} [built]
   [1] ./src/index.js 403 bytes {0} [built]
   [3] (webpack)/buildin/global.js 509 bytes {0} [built]
   [4] (webpack)/buildin/module.js 517 bytes {0} [built]
    + 1 hidden module
Child html-webpack-plugin for "index.html":
       [2] (webpack)/buildin/global.js 509 bytes {0} [built]
       [3] (webpack)/buildin/module.js 517 bytes {0} [built]
        + 2 hidden modules

  在瀏覽器打開index.html,點擊按鈕能夠看到以下輸出:瀏覽器

 Uncaught ReferenceError: cosnole is not defined
    at HTMLButtonElement.printMe (print.js:2)

  它會打印出錯誤信息和文件及位置,能夠說很是好用了。安全

選擇一個開發工具:

  ps:一些文本編輯器具備「安全寫入」功能,可能會干擾如下某些工具。閱讀官方的調整文本編輯器以解決這些問題。

  每次編譯代碼時手動運行npm run build會很麻煩,webpack裏有幾個選項能夠幫助你在代碼發生變化後自動編譯代碼:

  • webpack's Watch Mode
  • webpack-dev-server
  • webpack-dev-middleware

  大多數狀況下你會傾向於使用webpack-dev-server,可是瞭解全部選項也是很是有必要的。

使用觀察模式:

  你能夠指示webpack去監督你的依賴圖裏全部文件的變化。只要某個文件變化了就會自動編譯而不用你去手動編譯。來看看觀察模式怎麼配置:

package.json

  {
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
+     "watch": "webpack --watch",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "xml-loader": "^1.2.1"
    }
  }

  如今用npm run watch來看看這個模式怎麼編譯的,你會看到編譯碼,可是命令行不會退出了,由於webpack正在監督你的文件,作個改動試試:

src/print.js

  export default function printMe() {
-   cosnole.log('I get called from print.js!');
+   console.log('I get called from print.js!');
  }

  保存文件看一下控制檯應該就能夠發現webpack已經從新編譯了,惟一的缺點就是你得刷新你的瀏覽器瀏覽器,它要是會自動刷該多好,驚喜的是webpack-dev-server就會這麼幹。

使用webpack-dev-server:

  webpack-dev-server提供了一個簡單的web服務器來實現實時從新加載,老規矩須要安裝:

npm install --save-dev webpack-dev-server

  在配置文件中標明去哪查找文件:

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
  const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    mode: 'development',
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    devtool: 'inline-source-map',
+   devServer: {
+     contentBase: './dist'
+   },
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Development'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    }
  };

  這樣配置就等於告訴webpack-dev-server在localhost:8080下創建服務,而且去dist文件夾下查找文件。再加個腳本快捷運行服務:

package.json

  {
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "watch": "webpack --watch",
+     "start": "webpack-dev-server --open",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "xml-loader": "^1.2.1"
    }
  }

  ps:webpack-dev-server編譯後不會產生任何輸出文件,它只會保存打包後的存在於內存中的文件,而且會把它們當成掛載在服務器根目錄下的真實文件。若是你的頁面須要在別的目錄下查找到打包後的文件,能夠經過配置dev server的publicPath選項。

  如今運行npm start的話瀏覽器就會自動加載頁面了,並且你對某些文件作出改動並保存的話瀏覽器也會自動刷新。

使用webpack-dev-middleware:

  webpack-dev-middleware會把webpack處理後的文件發送給一個服務器。webpack-dev-server內部也使用了它,爲了知足一些自定義啓動需求它也能夠做爲一個單獨的包來使用,下面來看一個webpack-dev-middleware結合express服務器的例子。

  首先安裝:

npm install --save-dev express webpack-dev-middleware

  針對webpack-dev-middleware作一些配置改動:

webpack.config.js

  const path = require('path');
  const HtmlWebpackPlugin = require('html-webpack-plugin');
  const CleanWebpackPlugin = require('clean-webpack-plugin');

  module.exports = {
    mode: 'development',
    entry: {
      app: './src/index.js',
      print: './src/print.js'
    },
    devtool: 'inline-source-map',
    devServer: {
      contentBase: './dist'
    },
    plugins: [
      new CleanWebpackPlugin(['dist']),
      new HtmlWebpackPlugin({
        title: 'Output Management'
      })
    ],
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist'),
+     publicPath: '/'
    }
  };

  publicPath會在服務器腳本中用到來確保資源文件能在http://localhost:3000下正確訪問,端口號咱們以後再設置,先來配置一下express:

project

  webpack-demo
  |- package.json
  |- webpack.config.js
+ |- server.js
  |- /dist
  |- /src
    |- index.js
    |- print.js
  |- /node_modules

server.js

const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');

const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);

// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath
}));

// Serve the files on port 3000.
app.listen(3000, function () {
  console.log('Example app listening on port 3000!\n');
});

  來配置一下快捷啓動腳本:

package.json

  {
    "name": "development",
    "version": "1.0.0",
    "description": "",
    "main": "webpack.config.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "watch": "webpack --watch",
      "start": "webpack-dev-server --open",
+     "server": "node server.js",
      "build": "webpack"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "clean-webpack-plugin": "^0.1.16",
      "css-loader": "^0.28.4",
      "csv-loader": "^2.1.1",
      "express": "^4.15.3",
      "file-loader": "^0.11.2",
      "html-webpack-plugin": "^2.29.0",
      "style-loader": "^0.18.2",
      "webpack": "^3.0.0",
      "webpack-dev-middleware": "^1.12.0",
      "xml-loader": "^1.2.1"
    }
  }

  如今運行npm run server你應該能夠看到以下輸出:

Example app listening on port 3000!
...
          Asset       Size  Chunks                    Chunk Names
  app.bundle.js    1.44 MB    0, 1  [emitted]  [big]  app
print.bundle.js    6.57 kB       1  [emitted]         print
     index.html  306 bytes          [emitted]
...
webpack: Compiled successfully.

  打開瀏覽器前往http://localhost:3000就能夠看到項目正常運行了。

調整編輯器:

  使用自動編譯代碼功能的時候可能會在保存文件的時候遇到一些問題,有些編輯器有"安全寫入"功能可能會影響從新編譯,如下是禁用一些瀏覽器這個功能的方法:

  • Sublime Text 3 - 在用戶首選項(user preferences)中添加 atomic_save: "false"
  • IntelliJ - 在首選項(preferences)中使用搜索,查找到 "safe write" 而且禁用它。
  • Vim - 在設置(settings)中增長 :set backupcopy=yes
  • WebStorm - 在 Preferences > Appearance & Behavior > System Settings 中取消選中 Use "safe write"
相關文章
相關標籤/搜索