學webpack 3,看這篇文就夠了

此文檔使用webpack版本為 3.4.1,在你自行測試中,可能輸出結(jié)果與文檔中所貼出內(nèi)容不一致,請以你自己的代碼為準

安裝

本地安裝

npm install --save-dev webpacknpm install --save-dev webpack@[version]

全局安裝

npm install -g webpack

不推薦使用全局方式安裝,將會影響項目中所使用的webpack版本

起步

使用CLI(命令行)

創(chuàng)建一個目錄,并初始化package.json

mkdir webpack-test && cd webpack-test
npm init
npm install --save-dev webpack

構(gòu)建基本目錄及文件( / 代表目錄)

webpack-test
    -- /dist
        -- index.html
    -- package.json
    -- /src
        -- index.js

編輯index.js文件

function fun(){
    document.write("Hello Webpack");
}
fun();

編輯index.html文件

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="UTF-8">
    </head>
    <body>
    
    </body>
    <script src='bundle.js' charset='utf-8'></script>
</html>

在終端(工作目錄為當前項目目錄),輸入webpack src/index.js dist/bundle.js,并回車。

在你的終端應該會出現(xiàn)以下類似內(nèi)容:(內(nèi)容也許會有差異)

λ webpack src/index.js dist/bundle.js
Hash: 0f97cc36123f295c9fd2
Version: webpack 3.4.1
Time: 260ms
    Asset     Size  Chunks             Chunk Names
bundle.js  36.9 kB       0  [emitted]  main
   [0] ./src/index.js 84 bytes {0} [built]
   [1] multi ./src/index.js ./src/index.js ./dist/bundle.js 52 bytes {0} [built]
   [2] ./src/index.css 1.08 kB {0} [built]
   [3] ./node_modules/_css-loader@0.28.4@css-loader!./src/index.css 237 bytes {0} [built]
   [7] ./dist/bundle.js 18.4 kB {0} [built]
    + 3 hidden modules

運行index.html,可以看到頁面中的Hello Webpack。

使用配置文件

創(chuàng)建webpack.config.js文件

module.exports = {
    entry : "./src/index.js",
    output : {
        filename : "bundle.js",
        path : __dirname+"/dist"
    }
};

在終端輸入webpack --config webpack.config.js 或者直接輸入webpack,并回車

 webpack --config webpack.config.js
Hash: e2e4b7042538facd73f0
Version: webpack 3.4.1
Time: 216ms
    Asset     Size  Chunks             Chunk Names
bundle.js  18.4 kB       0  [emitted]  main
   [0] ./src/index.js 84 bytes {0} [built]
   [1] ./src/index.css 1.08 kB {0} [built]
   [2] ./node_modules/_css-loader@0.28.4@css-loader!./src/index.css 237 bytes {0} [built]
    + 3 hidden modules

使用npm

修改package.json文件中

{
...
"scripts": {
    "build": "webpack"
 },
...
}

在終端運行npm run build

使用source map

跟蹤代碼錯誤

修改webpack.config.js

//...省略
module.exports = {
    devtool : "inline-source-map",
    //...省略
}

修改index.js文件,故意生成一個錯誤

import "./index.css";
import wicon from "./webpack.png";
function fun(){
    console.log(a);
   //...省略
}

重新構(gòu)建,刷新頁面,在控制臺可以看到如下錯誤

Uncaught ReferenceError: a is not defined
    at fun (index.js:4)
    at Object.<anonymous> (index.js:10)
    at __webpack_require__ (bootstrap 403852e…:19)
    at module.exports (bootstrap 403852e…:62)
    at bootstrap 403852e…:62

可以看到,錯誤信息及錯誤所在文件和行數(shù)

開發(fā)模式

  • 觀察模式

    在終端輸入 webpack -wwebpack --watch

    會發(fā)現(xiàn)執(zhí)行構(gòu)建后,并沒有退出命令,此時正處理觀察模式

    可以在package.json的scripts配置項中增加如下內(nèi)容

    "scripts": {
        "watch" : "webpack --watch"
      },
    

    終端運行npm run watch 也能得到相同的效果

    ?

  • webpack-dev-server 即時刷新

    安裝

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

    修改webpack.config.js

    devServer : {
      contentBase : "./dist"
    }
    

    在終端輸入 webpack-dev-server 或 在package.json的scripts配置項中增加如下內(nèi)容并使用npm run dev:

    "scripts": {
        "watch": "webpack --watch",
        "dev": "webpack-dev-server --open"
      },
    

    會發(fā)現(xiàn)會自動打開瀏覽器,當有任意一個源文件被修改時,會自動重新刷新頁面

    ?

    **熱加載模式 **

    修改webpack.config.js

    const webpack = require("webpack");
    //...省略
    plugins : [
      new webpack.HotModuleReplacementPlugin()
    ],
      //...省略
    

    ?

    修改package.json的scripts配置項

    "scripts": {
        "watch": "webpack --watch",
        "dev": "webpack-dev-server --open --hot"
      }
    

    即可開啟hmr模式。即允許在運行時更新各模塊,而無需進行完全刷新

loader

CSS

style-loader css-loader

css-loader用于將css文件做為模塊處理,可以使用import 導入

style-loader 將所有處理完成的樣式插入到頁面的head中

安裝

npm install --save-dev style-loader css-loader

修改webpack.config.js

const path = require("path");
module.exports = {
    entry : "./src/index.js",
    output : {
        filename : "bundle.js",
        path : path.resolve(__dirname,"dist")
    },
    module : {
        rules : [{
            test : /\.css$/,
            use : ["style-loader","css-loader"]
        }]
    }
};

在src目錄下建立index.css文件

body{
    font-size : 50px;
    color : red;
}

修改index.js文件

import "./index.css";
//...省略

在終端執(zhí)行npm run build,刷新頁面

less | sass

less-loader sass-loader

npm install --save-dev less less-loader

圖片

file-loader

安裝

npm install --save-dev file-loader

修改webpack.config.js文件

//...省略
module : {
  rules : [{
    test : /\.css$/,
    use : ["style-loader","css-loader"]
  },{
    test : /\.(png|jpg|gif|jpeg)$/,
    use : ["file-loader"]
  }]
}
//...省略

修改index.css文件

.box{
    width: 497px;
    height:270px;
    background: url(./webpack.png)
}

修改index.html文件

<body>
   <div class="box"></div>
</body>

找一張你喜愛的照片拷貝至src目錄下,終端運行npm run build, 刷新頁面

繼續(xù)

修改index.js文件

import "./index.css";
import wicon from "./webpack.png";
function fun(){
    document.write("Hello Webpack");
    let img = new Image();
    img.src = wicon;
    document.body.appendChild(img);
}
fun();

重新執(zhí)行構(gòu)建,刷新頁面,你可以看到兩張圖片

JSON數(shù)據(jù)

JSON數(shù)據(jù)的加載是內(nèi)置的,可以通過 import mdata from './data.json', 即可正常使用

ES6 | JSX

babel-loader

安裝 由于babel是幾個模塊包,對于解析不同的語言需要安裝不同的包

常用的有如下:

cnpm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react

  • babel-core babel的核心包
  • babel-loader bable的Loader
  • babel-preset-es2015 轉(zhuǎn)換ES代碼
  • babel-preset-react 轉(zhuǎn)換JSX代碼

在src目錄新增other.js

export default function say(){
    console.log("hello!!!");
}

修改index.js

import say from "./other.js";
function fun(){
    say();
   //...省略
}

修改webpack.config.js

modules : {
  //...省略
  rules : [
    //...省略
    {
    test : /\.js$/,
      use : [{
        loader : "babel-loader",
        options : {
          presets : ["es2015"]
        }
      }]
  }]
}
//...省略

重新構(gòu)建,觀察控制臺

多文件入口

在src目錄增加home.js

function fun(){
    console.log("home is output");
}
fun();

修改index.html文件

<!DOCTYPE html>
<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <div class="box"></div>
    </body>
    <script src='./app.bundle.js' charset='utf-8'></script>
    <script src='./home.bundle.js' charset='utf-8'></script>
</html>

修改webpack.config.js

//...省略
entry: {
  app : "./src/index.js",
  home : "./src/home.js"
},
  output: {
    filename: "[name].bundle.js",
      path: __dirname + "/dist"
  },
//...省略

重新執(zhí)行構(gòu)建,并刷新頁面,觀察控制臺

問題:如果修改webpack.config.js中第7行filename一行所輸出的文件名稱,重新構(gòu)建,會發(fā)現(xiàn)在dist目錄會新增新名稱的文件,但index.html文件中依然引用的是舊的名字,如何解決?(參見 插件 htmlwebpackplugin)

插件

HtmlWebpackPlugin

自動生成頁面

安裝

npm install --save-dev html-webpack-plugin

修改webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
    entry: {
        //...省略
    },
    output: {
        //...省略
    },
    plugins : [
        new HtmlWebpackPlugin()
    ],
    module: {
        //...省略
    }
};

重新執(zhí)行構(gòu)建,并刷新頁面。

觀察dist目錄下的index.html,發(fā)現(xiàn)在測試file-loader時,創(chuàng)建div不見了,上述插件為我們創(chuàng)建一個新的html文件,并自動將output項所指定的filename引入到了頁面中

clean-webpack-plugin

清理dist目錄

安裝

npm install --save-dev clean-webpack-plugin --save-dev

修改webpack.config.js

const CleanWebpackPlugin = require("clean-webpack-plugin");
//...省略
plugins : [
  new HtmlWebpackPlugin(),
  new CleanWebpackPlugin(["dist"])
],
//...省略

重新執(zhí)行構(gòu)建,dist目錄清靜了

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容