webpack打包

在学习webpack之前先考虑如下几个问题

  1. jsx 转化为js
  2. es2016 转化为es2015
  3. import style from ‘./app.css’ 这种语法

Webpack的工作方式是:把你的项目当做一个整体,通过一个给定的主文件(如:index.js),Webpack将从这个文件开始找到你的项目的所有依赖文件,使用loaders处理它们,最后打包为一个(或多个)浏览器可识别的JavaScript文件。

webpack加上插件解决了上面的几个问题
webpack帮我们进行转化代码格式,帮我们计算依赖关系,最后把我们的代码打包到一起,从而可以部署到http服务器。

webpack配置使用

要理解的几个概念:
entry入口
output 打包的结果

loader:
css-loader
style-loader
babel-core
babel-loader ,babel-preset-react ,babel-preset-env
url-loader

plugin:
HtmlWebpackPlugin

一个简单的webpack的配置文件webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const path = require('path');


module.exports = {

    entry: "./src/index.js",
    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },

            {
                test: /\.css$/,
                use: [
                    {
                        loader: "style-loader"
                    },
                    {
                        loader: "css-loader",
                        options: {
                            modules: true,
                            importLoaders: 1,
                            localIdentName: "[name]_[local]_[hash:base64]",
                            sourceMap: true,
                            minimize: true
                        }
                    }
                ]
            }

        ]
    }
    ,
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Webpack-demos',
            template: "./src/index.html",
            filename: 'index.html'
        }),
    ]
}

posted @ 2022-03-06 10:39  叶常落  阅读(369)  评论(0编辑  收藏  举报