Webpack學習筆記

說明

這篇筆記是我學習lookroot在B站分享的Webpack教程的時候,對當時的配置文件進行了一個匯總,沒辦法,我真怕自己學完了也啥也不會。說來挺巧的,當時因為看到一些前端的招聘需求有Webpack,也不是什么太難的技術(shù),那就補補課唄。結(jié)果一下午安裝這玩意就搞了大半天,一步一個錯,很多教程都很老了,Webpack最近更新之后變化很大,API都會變。沒想到,這時候無意中發(fā)現(xiàn)了lookroot這個up主,就是就是最近一兩天剛剛更新的教程,于是我立即學習起來,學了兩遍吧,第一遍跟著做還一大堆bug,哭了。第二遍就還好5個小時左右就學完并且做完筆記了。在這里我分享一下它的教程鏈接,還有他的博客地址,希望對有需要的同學有幫助。

B站
博客

Webpack的安裝

①快速初始化項目:cnpm init -y
②安裝Webpack:cnpm i -D webpack
③安裝Webpack-cli:cnpm i -D webpack-cli

項目打包

手動打包一個文件

.\node_modules\.bin\webpack  // 并未制定打包模式
npx webpack --mode development // 用開發(fā)者模式打包
    - 注意:npx是.\node_modules\.bin目錄的簡寫

使用配置文件進行打包

配置文件:webpack.config.js

const path = require('path');


module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    // 目標文件
    entry: [path.resolve(__dirname, './src/index.js')],
    // 輸出文件
    output: {
        // 這里可以設(shè)置輸出文件的路徑和文件名
        path: path.resolve(__dirname, './dist'),
        filename: 'main.js'
    },
    // 插件
    plugins: [],
    // 模塊規(guī)則
    module: {
        
    }
}

然后運行這個命令就可以直接進行打包:

npx webpack

設(shè)置快捷命令

package.json文件:

在script中可以任意添加快捷命令

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

然后就可以用這種命令打包了:

npm run dev
npm run build

多個目標和輸出文件

注意:后面的所有小結(jié)我全部提供webpack.config.js和package.json兩個文件。這個小結(jié)僅僅修改了webpack.config.js中的entry和output

webpack.config.js:

const path = require('path');


module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    // 多個 目標文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 輸出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [],
    // 模塊規(guī)則
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

在Webpack中使用插件

html-webpack-plugin

作用:可以自動創(chuàng)建html文檔,并且引入js文件

安裝:

 cnpm i html-webpack-plugin -D

在webpack.config.js中導入和實例化插件

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    // 多個 目標文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 輸出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            title: 'webpack demo'
        })
    ],
    // 模塊規(guī)則
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

多頁面項目

說明:就是自動生成html文檔,并且不同的html文檔分別引入不同的JavaScript文件。

同樣是使用html-webpack-plugin插件

需要用html-webpack-plugin多實例化幾個,并且增加filename、chunks等屬性

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    // 多個 目標文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 輸出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模塊規(guī)則
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

sourcemap定位錯誤

作用:當代碼出現(xiàn)bug時,由于已經(jīng)進行打包無法定位原先在代碼中的錯誤,這個配置就可以解決這個問題

主要是在配置文件中使用devtool這個配置

  • 開發(fā)環(huán)境可以使用cheap-module-eval-source-mapeval 、eval-source-map
  • 生產(chǎn)環(huán)境可以使用inline-source-map、inline-cheap-module-source-mapcheap-source-map

webpack.config.js

僅僅是在mode下面新增加了一個devtool配置

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // 多個 目標文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 輸出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模塊規(guī)則
    module: {
        
    }
}

package.json

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

監(jiān)聽模式

作用:對代碼進行修改并且保存之后,自動進行重新打包。但是在實際開發(fā)中并不是用的這種模式。

package.json

僅僅需要在package.json中添加一行腳本就行

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12"
  }
}

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // 多個 目標文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 輸出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模塊規(guī)則
    module: {
        
    }
}

webpack-dev-server

作用:同樣是在代碼修改之后,自動進行打包,在通常的開發(fā)中都是使用這種模式

安裝webpack-dev-server

cnpm i webpack-dev-server -D

在package.json中配置server命令

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch",
    "server": "webpack-dev-server --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

在webpack.config.js中配置devServer

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // webpack-dev-server 的配置文件
    devServer: {
    /**
      * 日志模式  friendly-errors-webpack-plugin 插件可以優(yōu)化輸出
      * errors-only  只在發(fā)生錯誤時觸發(fā)
      * minimal 只在發(fā)生錯誤或者有新的編譯時輸出
      * none 沒有輸出
      * normal 標準輸出
      * verbose 全部輸出
      */
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
    },
    // 多個 目標文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 輸出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        })
    ],
    // 模塊規(guī)則
    module: {
        
    }
}

模塊熱更替

作用:之前,每次打包webpack就會把所有文件再次進行合并,如果項目過大,這個過程會非常消耗時間,使用模塊熱更替之后,每次修改文件也只會打包相應的文件。

這并不是一個插件,而是webpack內(nèi)置的

webpack.config.js

導入webpack;在plugins中進行實例化,在devServer中配置hot。

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
    // 當前環(huán)境 開發(fā)環(huán)境 development 生產(chǎn)環(huán)境  production
    mode: "development",
    devtool: "cheap-module-eval-source-map",
    // webpack-dev-server 的配置文件
    devServer: {
    /**
      * 日志模式  friendly-errors-webpack-plugin 插件可以優(yōu)化輸出
      * errors-only  只在發(fā)生錯誤時觸發(fā)
      * minimal 只在發(fā)生錯誤或者有新的編譯時輸出
      * none 沒有輸出
      * normal 標準輸出
      * verbose 全部輸出
      */
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
        hot: true
    },
    // 多個 目標文件
    entry: {
        index: path.resolve(__dirname, './src/index.js'),
        other: path.resolve(__dirname, './src/other.js')
    },
    // 輸出文件
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: '[name].bundle.js'
    },
    // 插件
    plugins: [
        new HTMLWebpackPlugin({
            filename: "index.html",
            title: "webpack demo",
            chunks: ['index']
        }),
        new HTMLWebpackPlugin({
            filename: "other.html",
            title: "webpack demo",
            chunks: ['other']
        }),
        new webpack.HotModuleReplacementPlugin(),
        // 告訴你哪個文件發(fā)生了變化
        new webpack.NamedModulesPlugin()
    ],
    // 模塊規(guī)則
    module: {
        
    }
}

package.json并未做任何修改

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch",
    "server": "webpack-dev-server --mode development"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0"
  }
}

開發(fā)環(huán)境和生產(chǎn)環(huán)境分離

作用:在真實的開發(fā)環(huán)境中,肯定是平時使用一套配置,項目上線使用另一套配置。

安裝插件

webpack-merge:自動將common分別和dev、prod配置文件進行合并

cnpm i webpack-merge -D

clean-webpack-plugin:自動刪除之前打包的文件

cnpm i clean-webpack-plugin -D

新建三個配置文件:

①:webpack.common.js

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


module.exports = {
    entry: [
        path.resolve(__dirname, './src/index.js')
    ],
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

②:webpack.dev.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
        hot: true
    }
})

③:webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: "production"
})

package.json中配置新的命令

{
  "name": "app4",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "watch": "webpack --mode development --watch",
    "server": "webpack-dev-server --mode development",
    "envdev": "webpack-dev-server --config webpack.dev.js",
    "envbuild": "webpack --config webpack.prod.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "html-webpack-plugin": "^4.3.0",
    "webpack": "^4.43.0",
    "webpack-cli": "^3.3.12",
    "webpack-dev-server": "^3.11.0",
    "webpack-merge": "^4.2.2"
  }
}

項目啟動

npm run envdev //用開發(fā)模式啟動
npm run envbuild // 用生產(chǎn)模式啟動項目

管理CSS

安裝插件

cnpm i style-loader css-loader -D

配置文件,主要是webpack.dev.js中添加了模塊規(guī)則

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
        hot: true
    },
    module: {
        rules: [{
            test: /\.css$/,
            use:['style-loader', 'css-loader']
        }]
    }
})

其余兩個配置文件均沒有做任何修改

webpack.common.js

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


module.exports = {
    entry: [
        path.resolve(__dirname, './src/index.js')
    ],
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: "production"
})

使用一個js文件向index文件中注入內(nèi)容

export default function divdoc(){
    let element = document.createElement("div");
    element.innerHTML = "webpack init";
    element.classList.add("init");
    document.body.appendChild(element);
}

CSS

.init {
    color: red;
    font-size: 48px;
}

index.js

import clg from './clg';
import divdoc from './js/divdoc';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("監(jiān)聽到clg.js文件修改")
    })
}

預處理

作用:配置完以后就可以將Less的代碼轉(zhuǎn)成CSS了

安裝插件

①:less加載器

cnpm i less-loader -D

配置文件:

webpack.dev.js

主要是添加新的模塊規(guī)則

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
        hot: true
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            }
        ]
    }
})

其余兩個配置文件保持不變

webpack.common.js

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


module.exports = {
    entry: [
        path.resolve(__dirname, './src/index.js')
    ],
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");

module.exports = merge(common, {
    mode: "production"
})

less文件

.init {
    color: red;
    font-size: 88px;
}

在index.js中導入less文件

import clg from './clg';
import divdoc from './js/divdoc';
import './css/app.less';
// import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("監(jiān)聽到clg.js文件修改")
    })
}

分離CSS

作用:之前的css處理都是直接插入到html文檔的開頭,但是如果樣式非常多就必須被單獨作為一個樣式文件被引入進來

安裝插件

①:迷你CSS提取器

cnpm i mini-css-extract-plugin -D

配置webpack.prod.js文件,主要是引入MiniCssExtractPlugin,然后進行實例化,配置模塊規(guī)則

const merge = require("webpack-merge")
const common = require("./webpack.common");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = merge(common, {
    mode: "production",
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'style/[name].css'
        }),
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use:[MiniCssExtractPlugin.loader, 'css-loader'] 
            }
        ]
    }
})

webpack.common.js

主要修改了入口這里的名字,這樣導出之后的,css才會變成index.css,否則的話,默認是main.css

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


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        }
    ,
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ]
}

webpack.dev.js

const merge = require("webpack-merge")
const common = require("./webpack.common");


module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
        hot: true
    },
      
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            }
        ]
    }
})

其它內(nèi)容文件

index.js

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("監(jiān)聽到clg.js文件修改")
    })
}

app.css

.init {
    color: red;
    font-size: 48px;
}

管理圖片

作用:主要是用來將某些比較小的圖片就直接采用base64碼的形式,減少內(nèi)存消耗

安裝插件

cnpm i file-loader -D
cnpm i url-loader -D

配置文件 webpack.common.js,主要是給圖片添加一個模塊規(guī)則

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


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        }
    ,
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        //超過這個大小,圖片就打包為圖片,不超過就打包為base64格式的代碼
                        limit: 1000000,
                        //打包文件名
                        name: "img/[hash].[ext]",
                    },
                }
            },
        ]
    }
}

使用js文件插入背景圖片

divdoc.js

import logo from "../assets/img/萌6.jpg"

export default function divdoc(){
    let element = document.createElement("img");
    element.src = logo;
    document.body.appendChild(element);
}

index.js

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("監(jiān)聽到clg.js文件修改")
    })
}

管理資源路徑

作用:真正的項目啟動之后,可能資源并不在同一臺服務器上,因此需要給各種資源配置合適的域名。

配置文件

webpack.common.js

主要修改了輸出output時候的域名路徑,其它配置文件請參考上面管理圖片一節(jié),是一樣的。

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


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        },
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, 'dist'),
        publicPath: "https://www.lookrot.cn/assets"
    },
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        //超過這個大小,圖片就打包為圖片,不超過就打包為base64格式的代碼
                        limit: 10000000000000000,
                        //打包文件名
                        name: "img/[hash].[ext]",
                    },
                }
            },
        ]
    }
}

代碼檢查

安裝eslint、loader、錯誤格式化插件

cnpm i eslint  eslint-loader eslint-friendly-formatter -D

新建配置文件.eslintrc.json

下面這段代碼最后的rules就可以禁止在代碼中使用 alert() 方法

{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 11,
        "sourceType": "module"
    },
    "rules": {
        "no-alert": 2
    }
}

webpack.dev.js 主要在模塊規(guī)則里新增了語法檢查的規(guī)則

const merge = require("webpack-merge")
const common = require("./webpack.common");
const path = require('path');


module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
        hot: true
    },
      
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            },
            {
                test: /\.js$/,
                loader: 'eslint-loader',
                enforce: 'pre',
                include: [path.resolve(__dirname, 'src')],
                options: {
                    formatter: require('eslint-friendly-formatter')
                }
            }
        ]
    }
})

在 index.js 中故意寫一個會出錯的代碼,也就是 alert()

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("監(jiān)聽到clg.js文件修改")
    })
}

alert("test");

其它配置文件

webpack.common.js

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


module.exports = {
    entry: 
        {
            index:path.resolve(__dirname, './src/index.js')
        },
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, 'dist'),
        // publicPath: "https://www.lookrot.cn/assets"
    },
    plugins: [
        new CleanWebpackPlugin(),
        new webpack.NamedChunksPlugin(),
        new HtmlWebpackPlugin({
            title: "webpack init"
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        //超過這個大小,圖片就打包為圖片,不超過就打包為base64格式的代碼
                        limit: 10000000000000000,
                        //打包文件名
                        name: "img/[hash].[ext]",
                    },
                }
            },
        ]
    }
}

webpack.prod.js

const merge = require("webpack-merge")
const common = require("./webpack.common");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = merge(common, {
    mode: "production",
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'style/[name].css'
        }),
    ],
    module: {
        rules: [
            // {
            //     test: /\.css$/,
            //     use:['style-loader', 'css-loader']
            // },
            // {
            //     test: /\.less$/,
            //     use:['style-loader', 'css-loader', 'less-loader']
            // }
            {
                test: /\.css$/,
                use:[MiniCssExtractPlugin.loader, 'css-loader'] 
            }
        ]
    }
})

babel代碼轉(zhuǎn)化

作用:將ES6及以上的代碼,轉(zhuǎn)化為ES5的代碼,主要是考慮瀏覽器的兼容性

安裝插件

cnpm i @babel/runtime -S
cnpm i  babel-loader  @babel/core @babel/preset-env @babel/plugin-transform-runtime -D

新建.babelrc配置文件

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "useBuiltIns": "usage",
                "corejs": 3,
                "targets": {
                    "browsers": [ "ie >= 8", "chrome >= 62" ]
                }
            }
        ]
    ]
}

webpack.dev.js

主要添加了babel-loader模塊規(guī)則

const merge = require("webpack-merge")
const common = require("./webpack.common");
const path = require('path');


module.exports = merge(common, {
    mode: 'development',
    devtool: 'eval',
    devServer: {
        stats: "errors-only",
        //默認地址 localhost
        host: process.env.HOST,
        //默認端口 8080
        port: process.env.PORT,
        //是否直接打開瀏覽器
        open: true,
        hot: true
    },
      
    module: {
        rules: [
            {
                test: /\.css$/,
                use:['style-loader', 'css-loader']
            },
            {
                test: /\.less$/,
                use:['style-loader', 'css-loader', 'less-loader']
            },
            {
                test: /\.js$/,
                loader: 'eslint-loader',
                enforce: 'pre',
                include: [path.resolve(__dirname, 'src')],
                options: {
                    formatter: require('eslint-friendly-formatter')
                }
            },
            {
                test: /\.js$/,
                use: [{
                    loader: 'babel-loader',
                }]
            }
        ]
    }
})

在index.js中寫一個箭頭函數(shù)

import clg from './clg';
import divdoc from './js/divdoc';
// import './css/app.less';
import './css/app.css';

// console.log("webpack init");

clg('webpack init');
divdoc();

if(module.hot){
    module.hot.accept('./clg.js', () => {
        console.log("監(jiān)聽到clg.js文件修改")
    })
}

alert("test");

// 可能寫得不對
var say = () => {
    console.log("say");
}

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

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