关于webpack:webpack入门

3次阅读

共计 1804 个字符,预计需要花费 5 分钟才能阅读完成。

  1. npm init -y 生成 packge.json。
  2. npm i webpack webpack-cli -D,这时候能够 npx webpack 打包。
  3. packge.json 文件 script 中退出
"dev": "webpack --config webpack.config.js"

新建 webpack.config.js

const path = require("path");   // webpack 外部办法 path 组件
module.exports = {
    entry: "./main.js", // 入口文件指定
    output: {
        // 进口文件配置 配置进口打包门路
    filename: "index.js", // 打包后的文件名称
    path: path.resolve(__dirname, "dist") //resolve 绝对路径引入
 }
};

配置完这 2 个文件就能够间接 npm run dev 打包了
4. 打包时主动生成 index.html
npm i -D html-webpack-plugin
webpack.config.js 中退出

// index.html 生成插件
const HtmlWebPackPlugin = require("html-webpack-plugin");  

module.exports = {
    plugins: [
        new HtmlWebPackPlugin({
            filename: "index.html", // 生成打包文件名
             template: "./index.html", // 模板门路
             minify: { // 生产模式能够进行配置
                 removeAttributeQuotes: true, // 删除 html 文件双引号
                 collapseWhitespace: true // 折叠控行
             },
            hash:true, // 增加哈希值~~~~
         })
    ],
}

5.css 模块,css 以行内的形式插入到 head 中
npm i -D –save css-loader style-loader
webpack.config.js 中退出

module.exports = {
    module: {
        rules: [
          {
            test: /.css$/,
            use: ["style-loader", "css-loader"] // 执行程序右 -> 左, 下 -> 上
          }
        ]
    }
}

6.css 抽离,css 以 link 标签形式插入到 head 里
npm i -D –save mini-css-extract-plugin

const MinCssExtractPlugin = require("mini-css-extract-plugin"); // css 抽离插件

module.exports = {
    plugins: [
        new MinCssExtractPlugin({filename: "index.css",})
    ],
    module: {
        rules: [
          {
            test: /.css$/,
            use: [
                MinCssExtractPlugin.loader, 
                "css-loader"
            ] // 执行程序右 -> 左, 下 -> 上
          }
        ]
    }
}

7. 打包图片
css 背景图
npm i -D url-loader
webpack.config.js 中退出

module.exports = {
    module: {
        rules: [
            {test: /.(png|svg|jpg|gif)$/,
                use: [loader: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]',
                ]
            },
        ]
    }
}

js
main.js 中退出

import vue from './src/img/vue.png'

window.onload = function(){var root = document.getElementById('root');
    var image = new Image();    // 创立 img 标签
     image.src = vue;           // 将 img 的 src 属性设置成咱们引入的图片
     root.append(image);
}

html
npm i -D html-withimg-loader
webpack.config.js 中退出

module.exports = {
    module: {
        rules: [
            {test: /.(html|htm)$/i,
                use: ['html-withimg-loader'] // 解析 html 中的图片资源
            },
            {test: /.(png|svg|jpg|gif)$/,
                use: [
                   loader: 'url-loader,
                   options: {esModule: false}
                ]
            },
        ]
    }
}
正文完
 0