目录
概念
Entry
Output
Loaders
Plugins
简单示例
首页 web前端 js教程 webpack打包器的简单介绍

webpack打包器的简单介绍

Jun 26, 2017 am 10:37 AM
web webpack 入门 打包 简单

概念

webpack是一个现代javascript应用程序的模块打包器。

当webpack处理你的应用程序时,它会递归构建一个依赖图(包含了你的应用程序所需要每个模块),然后把这些模块打包到少数几个budle文件中(通常是只有一个,会被浏览器加载,根据项目情况而定)。

这是令人难以置信的配置,但开始前,你只需要明白四个核心概念:entry、output、loaders、和plugins。

配置对象选项
webpack.config.js

const path = require('path');

module.exports = {
  // click on the name of the option to get to the detailed documentation
  // click on the items with arrows to show more examples / advanced options

  entry: "./app/entry", // string | object | array
  // Here the application starts executing
  // and webpack starts bundling

  output: {
    // options related to how webpack emits results

    path: path.resolve(__dirname, "dist"), // string
    // the target directory for all output files
    // must be an absolute path (use the Node.js path module)

    filename: "bundle.js?1.1.11", // string
    // the filename template for entry chunks

    publicPath: "/assets/", // string
    // the url to the output directory resolved relative to the HTML page

    library: "MyLibrary", // string,
    // the name of the exported library

    libraryTarget: "umd", // universal module definition
    // the type of the exported library

    /* Advanced output configuration (click to show) */
  },

  module: {
    // configuration regarding modules

    rules: [
      // rules for modules (configure loaders, parser options, etc.)

      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "app")
        ],
        exclude: [
          path.resolve(__dirname, "app/demo-files")
        ],
        // these are matching conditions, each accepting a regular expression or string
        // test and include have the same behavior, both must be matched
        // exclude must not be matched (takes preferrence over test and include)
        // Best practices:
        // - Use RegExp only in test and for filename matching
        // - Use arrays of absolute paths in include and exclude
        // - Try to avoid exclude and prefer include

        issuer: { test, include, exclude },
        // conditions for the issuer (the origin of the import)

        enforce: "pre",
        enforce: "post",
        // flags to apply these rules, even if they are overridden (advanced option)

        loader: "babel-loader",
        // the loader which should be applied, it'll be resolved relative to the context
        // -loader suffix is no longer optional in webpack2 for clarity reasons
        // see webpack 1 upgrade guide

        options: {
          presets: ["es2015"]
        },
        // options for the loader
      },

      {
        test: "\.html$",

        use: [
          // apply multiple loaders and options
          "htmllint-loader",
          {
            loader: "html-loader",
            options: {
              /* ... */
            }
          }
        ]
      },

      { oneOf: [ /* rules */ ] },
      // only use one of these nested rules

      { rules: [ /* rules */ ] },
      // use all of these nested rules (combine with conditions to be useful)

      { resource: { and: [ /* conditions */ ] } },
      // matches only if all conditions are matched

      { resource: { or: [ /* conditions */ ] } },
      { resource: [ /* conditions */ ] },
      // matches if any condition is matched (default for arrays)

      { resource: { not: /* condition */ } }
      // matches if the condition is not matched
    ],

    /* Advanced module configuration (click to show) */
  },

  resolve: {
    // options for resolving module requests
    // (does not apply to resolving to loaders)

    modules: [
      "node_modules",
      path.resolve(__dirname, "app")
    ],
    // directories where to look for modules

    extensions: [".js?1.1.11", ".json", ".jsx", ".css?1.1.11"],
    // extensions that are used

    alias: {
      // a list of module name aliases

      "module": "new-module",
      // alias "module" -> "new-module" and "module/path/file" -> "new-module/path/file"

      "only-module$": "new-module",
      // alias "only-module" -> "new-module", but not "module/path/file" -> "new-module/path/file"

      "module": path.resolve(__dirname, "app/third/module.js?1.1.11"),
      // alias "module" -> "./app/third/module.js?1.1.11" and "module/file" results in error
      // modules aliases are imported relative to the current context
    },
    /* alternative alias syntax (click to show) */

    /* Advanced resolve configuration (click to show) */
  },

  performance: {
    hints: "warning", // enum
    maxAssetSize: 200000, // int (in bytes),
    maxEntrypointSize: 400000, // int (in bytes)
    assetFilter: function(assetFilename) {
      // Function predicate that provides asset filenames
      return assetFilename.endsWith('.css') || assetFilename.endsWith('.js');
    }
  },

  devtool: "source-map", // enum
  // enhance debugging by adding meta info for the browser devtools
  // source-map most detailed at the expense of build speed.

  context: __dirname, // string (absolute path!)
  // the home directory for webpack
  // the entry and module.rules.loader option
  //   is resolved relative to this directory

  target: "web", // enum
  // the environment in which the bundle should run
  // changes chunk loading behavior and available modules

  externals: ["react", /^@angular\//],
  // Don't follow/bundle these modules, but request them at runtime from the environment

  stats: "errors-only",
  // lets you precisely control what bundle information gets displayed

  devServer: {
    proxy: { // proxy URLs to backend development server
      '/api': 'http://localhost:3000'
    },
    contentBase: path.join(__dirname, 'public'), // boolean | string | array, static file location
    compress: true, // enable gzip compression
    historyApiFallback: true, // true for index.html upon 404, object for multiple paths
    hot: true, // hot module replacement. Depends on HotModuleReplacementPlugin
    https: false, // true for self-signed, object for cert authority
    noInfo: true, // only errors & warns on hot reload
    // ...
  },

  plugins: [
    // ...
  ],
  // list of additional plugins


  /* Advanced configuration (click to show) */
}
登录后复制

本文档的目的是给这些概念提供一个高层次的大纲,同时提供链接给详细概念的指定用例。

Entry

webpack会创建一个你所有应用程序的依赖图。这个依赖图的起始点就是已知的entry(入口)点。这个入口点告诉webpack从哪开始,并且根据已知依赖图进行打包。你可以把应用程序的入口点当作上下文根或启动你的应用程序的第一个文件。

在webpack配置对象的entry属性中定义入口点。简单示例如下:

module.exports = {
  entry: './path/to/my/entry/file.js'
};
登录后复制

有几种方式声明entry属性:

1、单个entry语法

const config = {
  entry: './path/to/my/entry/file.js'
};

module.exports = config;
登录后复制

2、对象语法

const config = {
  entry: {
    app: './src/app.js',
    vendors: './src/vendors.js'
  }
};
登录后复制

3、多页面应用

const config = {
  entry: {
    pageOne: './src/pageOne/index.js',
    pageTwo: './src/pageTwo/index.js',
    pageThree: './src/pageThree/index.js'
  }
};
登录后复制

Output

一旦你打包所有代码,你仍需要告诉webpack打包到哪里去。output属性会告诉webpack如何对待你的代码。

const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
};
登录后复制

以上这个例子,我们使用output.filenameoutput.path属性告诉webpack打包的文件名和路径

更多配置项

Loaders

这个配置项的目的是让webpack关注你项目的所有代码而非浏览器(这并不意味着它们会被打包到一起)。webpack把每一个文件(.css, .html, .scss, .jpg, etc.)作为一个模块。然而,webpack只知道javascript。

webpack中的Loaders会转换这些文件到模块中,并添加到你的依赖图中。

在一个较高的水平,在你的webpack配置中有两个目的:
1、标识什么文件应该用一个确定的loader来转换。
2、转换后的文件可以被添加到你的依赖图中。

const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      {test: /\.(js|jsx)$/, use: 'babel-loader'}
    ]
  }
};

module.exports = config;
登录后复制

以上这个配置定义了一个rulues属性,用以给一个单独的模块,这个模块带有两个属性:test和use。这告诉webpack编译如下事情:
当使用require()或import语句时,路径中后缀名为.js或.jsx的文件,使用babel-loader来转换并打包。

更多配置项

Plugins

因为加载器只执行基于每个文件的转换,插件是最常用的(但不限于)优化行为,并且你可以自定义函数在你打包模块的编辑或块中(等等)。
该webpack插件系统极其强大,可定制。

为了使用一个插件,你只需要require()并添加到插件数组中。更多插件可通过选项自定义。由于你可以在一个配置中多次使用插件来达到不同的目的,因此你需要创建一个新的实例。

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

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      {test: /\.txt$/, use: 'raw-loader'}
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

module.exports = config;
登录后复制

webpack提供有许多开箱插件!可以从我们的插件列表中获得更多信息。

在webpack配置中使用插件是简单的,然而有许多用法值得进一步探讨。

更多配置项

简单示例

var path = require('path');
var webpack = require('webpack');

var env = process.env.NODE_DEV;

var config = {
    entry: {
        consumer: './consumer/index.js',
        admin: './admin/index.js',
        // jquery: ['jquery']
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/dist/',
        filename: '[name].bundle.js'
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: 'style-loader!css-loader' },
            { test: /\.less$/, loader: 'less-loader!style-loader!css-loader' },
            { test: /\.sass$/, loader: 'sass-loader!style-loader!css-loader' },
            { test: /\.(woff|woff2|eot|ttf|otf)$/i, loader: 'url-loader?limit=8192&name=[name].[ext]' },
            { test: /\.(jpe?g|png|gif|svg)$/i, loader: 'url-loader?limit=8192&name=[name].[ext]' },
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                include: __dirname,
                options: {
                    presets: ['es2015', 'react']
                },
            },
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                exclude: /node_modules/,
                include: __dirname
            },
            {
                test: /\.coffee$/,
                loader: 'coffee-loader',
                exclude: /node_modules/,
                include: __dirname
            }
        ]
    },
    //devtool: 'source-map',
    //指定根路径
    context: __dirname,
    //这里枚举的后缀名,在require时可以省略
    resolve: {
        extensions: ['.js', '.jsx', '.json', '.ts', '.tsx', '.css']
    },
    plugins: [
        // 这里声明的变量是全局的,可以在所有的js中使用,可以避免写一堆的require
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.$': 'jquery',
            'React': 'react',
            'ReactDOM': 'react-dom'
        }),
        // new webpack.optimize.CommonsChunkPlugin({
        //     // 与 entry 中的 jquery 对应
        //     name: 'jquery',
        //     // 输出的公共资源名称
        //     filename: 'jquery.min.js',
        //     // 对所有entry实行这个规则
        //     minChunks: Infinity
        // }),
        // new webpack.NoEmitOnErrorsPlugin()
    ],
    //在html页面中使用script标签引入库,而不是打包到*.bundle.js文件中
    externals: {
        jquery: 'jQuery',
        react: 'React',
        'react-dom' : 'ReactDOM'
    }
};

//如果是生产环境,要最小化压缩js文件
if (env === 'production') {
    //打包时对js文件进行最小化压缩
    config.plugins.push(new webpack.optimize.UglifyJsPlugin({
        mangle: {
            except: ['$super', '$', 'exports', 'require']
            //以上变量‘$super’, ‘$’, ‘exports’ or ‘require’,不会被混淆
        },
        compress: {
            warnings: false
        }
    }));
    //消除压缩后的文件在界面引用时发出的警告
    config.plugins.push(new webpack.DefinePlugin({
        'process.env': {
            NODE_ENV: JSON.stringify('production')
        }
    }));
}

module.exports = config;
登录后复制

以上是webpack打包器的简单介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

最简便的硬盘序列号查询方式 最简便的硬盘序列号查询方式 Feb 26, 2024 pm 02:24 PM

硬盘序列号是硬盘的一个重要标识,通常用于唯一标识硬盘以及进行硬件识别。在某些情况下,我们可能需要查询硬盘序列号,比如在安装操作系统、查找正确设备驱动程序或进行硬盘维修等情况下。本文将介绍一些简单的方法,帮助大家查询硬盘序列号。方法一:使用Windows命令提示符打开命令提示符。在Windows系统中,按下Win+R键,输入"cmd"并按下回车键即可打开命

值得你花时间看的扩散模型教程,来自普渡大学 值得你花时间看的扩散模型教程,来自普渡大学 Apr 07, 2024 am 09:01 AM

Diffusion不仅可以更好地模仿,而且可以进行「创作」。扩散模型(DiffusionModel)是一种图像生成模型。与此前AI领域大名鼎鼎的GAN、VAE等算法,扩散模型另辟蹊径,其主要思想是一种先对图像增加噪声,再逐步去噪的过程。其中如何去噪还原原图像是算法的核心部分。最终算法能够从一张随机的噪声图像中生成图像。近年来,生成式AI的惊人增长将文本转换为图像生成、视频生成等领域的许多令人兴奋的应用提供了支持。这些生成工具背后的基本原理是扩散的概念,这是一种特殊的采样机制,克服了以前的方法中被

一键生成PPT!Kimi :让「PPT民工」先浪起来 一键生成PPT!Kimi :让「PPT民工」先浪起来 Aug 01, 2024 pm 03:28 PM

Kimi:一句话,十几秒钟,一份PPT就新鲜出炉了。PPT这玩意儿,可太招人烦了!开个碰头会,要有PPT;写个周报,要做PPT;拉个投资,要展示PPT;就连控诉出轨,都得发个PPT。大学更像是学了个PPT专业,上课看PPT,下课做PPT。或许,37年前丹尼斯・奥斯汀发明PPT时也没想到,有一天PPT竟如此泛滥成灾。吗喽们做PPT的苦逼经历,说起来都是泪。「一份二十多页的PPT花了三个月,改了几十遍,看到PPT都想吐」;「最巅峰的时候,一天做了五个PPT,连呼吸都是PPT」;「临时开个会,都要做个

CVPR 2024全部奖项公布!近万人线下参会,谷歌华人研究员获最佳论文奖 CVPR 2024全部奖项公布!近万人线下参会,谷歌华人研究员获最佳论文奖 Jun 20, 2024 pm 05:43 PM

北京时间6月20日凌晨,在西雅图举办的国际计算机视觉顶会CVPR2024正式公布了最佳论文等奖项。今年共有10篇论文获奖,其中2篇最佳论文,2篇最佳学生论文,另外还有2篇最佳论文提名和4篇最佳学生论文提名。计算机视觉(CV)领域的顶级会议是CVPR,每年都会吸引大量研究机构和高校参会。据统计,今年共提交了11532份论文,2719篇被接收,录用率为23.6%。根据佐治亚理工学院对CVPR2024的数据统计分析,从研究主题来看,论文数量最多的是图像和视频合成与生成(Imageandvideosyn

从裸机到700亿参数大模型,这里有份教程,还有现成可用的脚本 从裸机到700亿参数大模型,这里有份教程,还有现成可用的脚本 Jul 24, 2024 pm 08:13 PM

我们知道LLM是在大规模计算机集群上使用海量数据训练得到的,本站曾介绍过不少用于辅助和改进LLM训练流程的方法和技术。而今天,我们要分享的是一篇深入技术底层的文章,介绍如何将一堆连操作系统也没有的「裸机」变成用于训练LLM的计算机集群。这篇文章来自于AI初创公司Imbue,该公司致力于通过理解机器的思维方式来实现通用智能。当然,将一堆连操作系统也没有的「裸机」变成用于训练LLM的计算机集群并不是一个轻松的过程,充满了探索和试错,但Imbue最终成功训练了一个700亿参数的LLM,并在此过程中积累

AI在用 | AI制作独居女孩生活Vlog,3天狂揽上万点赞量 AI在用 | AI制作独居女孩生活Vlog,3天狂揽上万点赞量 Aug 07, 2024 pm 10:53 PM

机器之能报道编辑:杨文以大模型、AIGC为代表的人工智能浪潮已经在悄然改变着我们生活及工作方式,但绝大部分人依然不知道该如何使用。因此,我们推出了「AI在用」专栏,通过直观、有趣且简洁的人工智能使用案例,来具体介绍AI使用方法,并激发大家思考。我们也欢迎读者投稿亲自实践的创新型用例。视频链接:https://mp.weixin.qq.com/s/2hX_i7li3RqdE4u016yGhQ最近,独居女孩的生活Vlog在小红书上走红。一个插画风格的动画,再配上几句治愈系文案,短短几天就能轻松狂揽上

技术入门者必看:C语言和Python难易程度解析 技术入门者必看:C语言和Python难易程度解析 Mar 22, 2024 am 10:21 AM

标题:技术入门者必看:C语言和Python难易程度解析,需要具体代码示例在当今数字化时代,编程技术已成为一项越来越重要的能力。无论是想要从事软件开发、数据分析、人工智能等领域,还是仅仅出于兴趣学习编程,选择一门合适的编程语言是第一步。而在众多编程语言中,C语言和Python作为两种广泛应用的编程语言,各有其特点。本文将对C语言和Python的难易程度进行解析

细数RAG的12个痛点,英伟达高级架构师亲授解决方案 细数RAG的12个痛点,英伟达高级架构师亲授解决方案 Jul 11, 2024 pm 01:53 PM

检索增强式生成(RAG)是一种使用检索提升语言模型的技术。具体来说,就是在语言模型生成答案之前,先从广泛的文档数据库中检索相关信息,然后利用这些信息来引导生成过程。这种技术能极大提升内容的准确性和相关性,并能有效缓解幻觉问题,提高知识更新的速度,并增强内容生成的可追溯性。RAG无疑是最激动人心的人工智能研究领域之一。有关RAG的更多详情请参阅本站专栏文章《专补大模型短板的RAG有哪些新进展?这篇综述讲明白了》。但RAG也并非完美,用户在使用时也常会遭遇一些「痛点」。近日,英伟达生成式AI高级解决

See all articles