buiildToolStudy/webpackTest/README.md

2.4 KiB
Raw Permalink Blame History

初始化项目

npm init -y

安装webpack依赖开发依赖

npm add -D webpack webpack-cli

打包项目

npx webpack

entery 入口文件

入口文件是webpack的起点通过入口文件来找到项目中的所有依赖模块。

module.exports = {
    entry: './src/index.js', //默认值
    entry"./hello/hello.js", // 修改默认值
    entry: ["./src/a.js", "./src/b.js"], // 多个入口文件
    entry: {
      hello: "./src/a.js",
      b: "./src/b.js"
    } // 多个入口文件,使用对象形式
}

output 出口文件

出口文件是webpack打包后输出的文件。

module.exports = {
    output: {
        filename: "bundle.js", // 默认值
        clean: true, // 清除打包文件所在目录
        path: `${__dirname}/dist/dist` // 指定打包后的文件路径
    }
}

loader

需要安装css-loader、style-loader

module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader', // loader 执行顺序是从右到左
                ]
            },
            {
                test: /\.(png|jpg|jpeg|gif)$/,
                type: 'asset/resource' // 图片资源类型
            }
        ]
    }
}

babel

安装babel依赖开发依赖

npm add -D @babel/core @babel/preset-env babel-loader

配置babel

 module: {
        rules: [
            {
                test: /\.m?js$/,
                exclude: /(node_modules | bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    }

plugin 插件

例如:html-webpack-plugin

npm add -D html-webpack-plugin
const HtmlWebpackPlugin = require('html-webpack-plugin')
 module: {
    plugins: [
        new HtmlWebpackPlugin({
            // template: './src/index.html'
            // filename: 'index.html',
            // template: './src/index.html'
            title: 'webpack-demo',
        })
    ]
}

Webpack 开发服务器

npm add -D webpack-dev-server
module.exports = {
    devServer: {
        port: 7000,
    }
}