webpack1學習筆記

幸運兒發表於2019-02-16

基本介紹

引入檔案

// a.js
require(`./b.js`)
require(`style-loader!css-loader!./a.css`)

打包檔案

// cli
webpack hello.js hello.bundle.js --module-bind `css=style-loader!css-loader!`

預覽html

// html
<script src=`./a.bundle.js`></script>

webpack選項引數
–watch
–progress
–display-modules
–display-reasons
–color
–display-error-details

基本配置

建立專案
mkdir webpack-demo
cd webpack-demo
npm init
npm install webpack –save-dev
mkdir src
mkdir dist
vsc //vscode
建立html並引入bundle.js
建立webpack.config.js//可參考官網配置API

//模組化輸出
module.exports={
    // 
    entry:`./src/script/main.js`,
    output:{
        path:`./dist/js`,
        filename:`bundle.js`
    },
}
//cli
webpack --config webpack.dev.config.js//指定config檔案為webpack.dev.config.js
//

詳解entry和output

entry的3種:單一字串,陣列,物件
output根絕entry不同而不同
【陣列】
main和sub-main打包成bundle

module.exports={
    entry:[
    `./src/script/main.js`,
    `./src/script/sub-main.js`
    ],
    output:{
        path:`./dist/js`,
        filename:`bundle.js`
    },
}

【物件】–多頁面應用
main和打包成bundle

module.exports={
    entry:{
        page1:`./src/script/main.js`,
        page2:[
            `./src/script/main.js`,
            `./src/script/sub-main.js`
        ],    
    },
    output:{
        path:`./dist/js`,
        //【佔位符】hash本次 chunkhash靜態資源改變後才變化
        filename:`[name]-[hash]-[chunkhash].js`
    },
}

使用外掛

html-wabpack-plugin

作用:同步html內引入的js的chunkhash

//cli
npm install html-wabpack-plugin --save-dev
//webpack.config.js
var htmlWebpackPlugin=require(`html-wabpack-plugin`)
module.exports={
    // 上下文的預設環境就是當前執行指令碼的目錄
    // context:
    entry:{
        page1:`./src/script/main.js`,
        page2:[
            `./src/script/main.js`,
            `./src/script/sub-main.js`
        ],    
    },
    output:{
        path:`./dist`,
        // js
        filename:`js/[name]-[hash]-[chunkhash].js`,
        // 上線環境的
        publicPath:`http://m.mi.com/`
    },
    // 所有plugin都輸出到output.path
    plugin:[
        //初始化外掛 並傳入相關引數
        new htmlWebpackPlugin({
            // 上下文環境 以根目錄html作為模板 
            template:`index.html`,
            filename:`index-[hash].html`,
            inject:`head`,//不配置的話 預設放到body標籤內
            //向html裡面傳參,
            //在html用<%= htmlWebpackPlugin.options.title %>接收
            title:`haha`,//date:new Date(),
            //壓縮html 刪除註釋和空格
            minify:{
                removeComments:true,
                collapseWhitespace:true
            }
        });
    ]
}

<!-- index.html -->
<!-- 可以編寫js的模板引擎<%= 賦值 %><% 執行 %> -->

<% for (var key in htmlWebpackPlugin.files) {%>
<%= key %> : <%= JSON.stringify(htmlWebpackPlugin.files[key]) %>
<% } %>

<% for (var key in htmlWebpackPlugin.options) {%>
<%= key %> : <%= JSON.stringify(htmlWebpackPlugin.files[key]) %>
<% } %>

<!-- 用處 -->
<script src="<%= htmlWebpackPlugin.files.chunks.main.entry%>"></script>