本身動手搭建webpack

wepack初探

從頭整理webpack搭建流程html

webpack主要配置

  • entry:入口配置
  • output:輸出配置
  • module:文件解析模塊配置
  • plugin:插件配置

目錄介紹

  • build/:存放webpack構建配置文件
  • src/:項目開發目錄webpack

    • public/:公共靜態文件
    • script/:腳本文件
    • style/:樣式文件
    • view/:頁面文件

初始npm包

開發依賴web

  • babel-core
  • babel-loader
  • webpack:這裏使用webpack3版本

開始搭建

  1. build/文件夾下面建立webpack.dev.js,代碼以下:npm

    const path = require('path')
    
    module.exports = {
        entry: path.join(__dirname, '../src/script/index.js'),
        output: {
            path: path.join(__dirname, '../dist'),
            filename: 'js/[name].js'
        },
        module: {
            loaders: [{
                test: /\.js$/,
                use: 'babel-loader'
            }]
        }
    }
  2. src/script/文件夾下面建立index.js,任意寫幾行代碼以便測試
  3. src/view/文件夾下面建立index.html,引入上面的index.js文件
  4. npm init -y或者yarn init -y建立package.json文件,安裝開發依賴
  5. package.json文件中添加scripts屬性json

    "scripts": {
        "dev": "rm -rf dist & webpack --config build/webpack.dev.js"
    }

打開終端執行npm run dev命令babel

圖片描述

引入html-webpack-plugin插件測試

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

module.export = {
    entry: path.join(__dirname, '../src/script/index.js'),
    output: {
        path: path.join(__dirname, '../dist'),
        filename: 'js/[name].js'
    },
    module: {
        loaders: [{
            test: /\.js$/,
            use: 'babel-loader'
        }]
    },
    plugins: [
        new HtmlWebpackPlugin({
            // 打包生成html文件名,該文件被放置在輸出目錄中
            filename: 'index.html',
            // 模板文件,以該文件生成打包後的html文件
            template: path.join(__dirname, '../src/view/index.html')
        })
    ]
}
相關文章
相關標籤/搜索