Webpack - 基本配置

webpack - 最熱門的前端資源模塊化管理打包工具

簡單設(shè)置(單頁面)

  • 先安裝webpack npm install webpack --save-dev.
  • 在package.json里添加寫腳本方便使用.
"webpack": "webpack --config webpack.config.js --progress --display-modules --colors --display-reason"
  • npm run webpack 就可以起到--config webpack.config.js效果.

  • webpack.config.js文件配置如下:

      //先安裝htmlwebpackplugin npm install htmlwebpackplugin --save-dev
      var htmlWebpackPlugin = require('html-webpack-plugin');
      module.exports = {
      // context:上下文環(huán)境 = 根目錄,
      entry: {
          main:'./src/js/main.js',
          bain: './src/js/bain.js'
      },
      output: {
          //輸出路徑
          path: './dist',
          //這里的[hash][chunkhash]指的其實(shí)就是版本號,MD5算法保證文件的唯一性
          filename: 'js/[name]-[chunkhash].js',
          //代碼發(fā)布時的 地址
          publicPath: 'http://aili.com/'
      },
      
      plugins: [
          new htmlWebpackPlugin({
              // filename: 'index-[hash].html',filename: 'index-[chunkhash].html',生成后的文件名
              filename: 'index.html',
              //模板文件,就是項(xiàng)目根目錄的index.html
              template: 'index.html',
              //將引入文件插入到哪里,body,head,false
              inject: 'body',
              title:'webpack is fuck',
              date: new Date(),
              //插件的參數(shù): 刪除注釋空格之類的其他可以去插件官網(wǎng)找
              minify:{
                  removeComments:true,
                  collapseWhitespace: true
                  }
              })
          ]
      }
    

    htmlwebpackplugin
    htmlwebpackplugin.minify

多頁面設(shè)置

分別有a.js,b.js,c.js

var htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
// context:,
entry: {
    main:'./src/js/main.js',
    // bain: './src/js/bain.js',
    a: './src/js/a.js',
    b: './src/js/b.js',
    c: './src/js/c.js'
},
output: {
    path: './dist',
    filename: 'js/[name].js',
    publicPath: 'http://aili.com/'
},

plugins: [
    new htmlWebpackPlugin({
        // filename: 'index-[hash].html',
        filename: 'index.html',
        template: 'index.html',
        inject: 'body',
        title:'webpack is fuck',
        date: new Date(),
        minify:{
            removeComments:true,
            collapseWhitespace: true
        }
    }),
    new htmlWebpackPlugin({
        // filename: 'index-[hash].html',
        filename: 'a.html',
        template: 'index.html',
        // inject: 'body',
        inject: false,
        title:'This is a.html',
        //chunks:引用哪些js,這里用到的公用main.js和a.js
        chunks: ['main','a']
    }),
    new htmlWebpackPlugin({
        // filename: 'index-[hash].html',
        filename: 'b.html',
        template: 'index.html',
        // inject: 'body',
        inject: false,
        title:'This is b.html',
        chunks: ['main','b']
    }),
    new htmlWebpackPlugin({
        // filename: 'index-[hash].html',
        filename: 'c.html',
        template: 'index.html',
        // inject: 'body',
        inject: false,
        title:'This is c.html',
        chunks: ['main','c']
    }),
]
}

這里遇到一個問題,公用的main和對應(yīng)的各個js不用htmlwebpackplugin.chunks怎么實(shí)現(xiàn)?

  • 可以自己配置個參數(shù)然后循環(huán)plugins判斷是否是當(dāng)前配置的參數(shù)

    new htmlWebpackPlugin({
    // filename: 'index-[hash].html',
    filename: 'a.html',
    template: 'index.html',
    inject: 'body',
    title:'This is a.html',
    //自定義參數(shù)
    isThat_a:true
    })
    然后再對應(yīng)的文件下(這里是a.js)循環(huán)插件參數(shù)

    <% for(var key in htmlWebpackPlugin.options){%>
    <%= key%> : <%= JSON.stringify(htmlWebpackPlugin.options[key])%>
    if(isThat_a){<script type="text/javascript" src="<%= htmlWebpackPlugin.files.chunks.a.entry %>">
    </script>}
    <%}%>

Loaders

loader - Babel

loader使用方法 - 其中介紹了三種方法 require configuration cli.

  • require:

      require("./loader!./dir/file.txt");
      require("jade!./template.jade");
      require("!style!css!less!bootstrap/less/bootstrap.less");
    
  • configuration:

      {
          module: {
              loaders: [
                  { test: /\.jade$/, loader: "jade" },
                  // => "jade" loader is used for ".jade" files
                  { test: /\.css$/, loader: "style!css" },
                  // => "style" and "css" loader is used for ".css" files
                  // Alternative syntax:
                  { test: /\.css$/, loaders: ["style", "css"] },
              ]
          }
      }
    

    我用了第二種(configuration),先下載babel npm install babel--save-dev.更改配置文件

    Babel-官網(wǎng)插件 - 這里用到的插件presets.當(dāng)然得先下載npm install babel-preset-latest(這里可以是2015 2016 2017 latest).

      var htmlWebpackPlugin = require('html-webpack-plugin');
      //引用nodejs自帶的path模塊
      var path = require('path');
      module.exports = {
      context:__dirname,
      entry: './src/app.js',
      output: {
          path: './dist',
          filename: 'js/[name].bundle.js',
      },
      module: {
          loaders:[
              {
                  //js
                  test:/\.js$/,
                  loader:'babel',
                  //tigao 打包速度
                  exclude:path.resolve(__dirname, "node_modules"),
                  //include:'./src',
                  query:{
                      presets:['latest']
                  }
              }
          }
      ]
      },
      plugins: [
      new htmlWebpackPlugin({
          // filename: 'index-[hash].html',
          filename: 'index.html',
          template: 'index.html',
          inject: 'body'
      })
      ]
      }
    

loader - css

  • npm install style-loader+css-loader+postcss-loader+autoprefixer --save-dev
    其中:

      loader: "style-loader!css-loader!'postcss-loader" ,
      loader:['style-loader','css-loader','postcss-loader'] //這兩個寫法一樣
    

autoprefixer調(diào)用方法:在根目錄下添加postcss.config.js文件或在webpack.config.js文件里增加postcss模塊

    module.exports = {
    plugins: [
        require('autoprefixer')({ browsers: ["last 5 versions"] })
    ] 
    }
增加postcss模塊

loader - less+sass

分別安裝less sass

  • npm install less -save-dev

  • npm install less-loader --save-dev

    {
    test: /.less$/,
    loader: "style-loader!css-loader!postcss-loader!less-loader"
    }

loader - HTML

npm-install html-loader --save-dev

寫個layer.js

import tpl from './layer.html';
import './layer.less';

function layer(){
    return {
        name:'layer',
        tpl:tpl
    };
    alert("Im layer");
}

export default layer;

layer.html

<div class="layer">
    <div>This is Layer!!!</div>
</div>

app.js(入口js)

import './css/common.css';
import layer from './components/layer/layer.js';
const App = function (){
    var dom = document.getElementById("app");
    var layer_r = new layer();
    dom.innerHTMl = layer_r;
}

new App();

然后直接在index.html中定義好用這個模塊的加載點(diǎn)就ok.(<div id="app"></div>)
its work!! amazing man
[圖片上傳失敗...(image-962629-1529468515878)]

loader - template

這里我用ejs模板 npm install ejs-loader --save-dev

{
    test: /\.tpl$/,   //這里可以自定義文件后綴,只用定義加載的模板文件即可
    loader: "ejs-loader"
}

layer.tpl

<div class="layer">
 <div>  this is the mustache-syntax - {{ this is the <%= name %> layer}}
<br/>
<% for(var i = 0;i<arr.length;i++) {%>
    <%= arr[i]%>
<%}%>
</div>
</div>

layer.js

import tpl from './layer.tpl';
import './layer.less';

function layer(){
    return {
        name:'layer',
        tpl:tpl
    };
    alert("Im layer");
}

export default layer;

app.js

import './css/common.css';
import layer from './components/layer/layer.js';
const App = function (){
    var dom = document.getElementById("app");
    var layer_r = new layer();
    dom.innerHTML=layer_r.tpl({         //這里對象里的值就是在 layer.js中定義的對象。
        name:'My name is Aili',  
        arr:['webpack','grunt','gulp']
    });
}

new App();

its work!!!


image

loader - image

圖片有三種引用方式

  • 模板文件用 <img>
  • css - background
  • 還有index.html <img>
  • npm install file-loader --save-dev

webpack.config.js:

{
    test:/\.(png|jpg|gif|svg)$/i,
    loader:"file-loader"
}

模板文件用到的圖片要做點(diǎn)處理:
本應(yīng)是(<img src = "相對地址"> ---> <img src="${ require('相對地址') }" />)

最后優(yōu)化圖片加載 - file-loader(更改打包后文件的存放地址)+url-loader(轉(zhuǎn)換為編碼)+image-webpack-loader(壓縮圖片) 這三個配合使用效果更好。
so npm install 剩余的兩個loader即可
所以最后配置文件變成了:

{
    test:/\.(png|jpg|gif|svg)$/,
    //url-loader的param: limit:圖片壓縮后大小超過1k,就轉(zhuǎn)換成base64編碼。
    loaders:["url-loader?limit:1000&name:assets/[name]-[hash:5].[ext]","image-webpack-loader"]
}

這只是打包和loader的基本配置,后續(xù)我在更新成開發(fā)環(huán)境的hot-reload等插件,webpack小白一枚。

代碼地址

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容