zoukankan      html  css  js  c++  java
  • webpack初识

    1 .首先建一个项目文件夹webpack_test

    2. 然后生成一个package.json文件,这里就用npm init 一路回车就ok

    3. 下一个webpack的包,cnpm install webpack --save-dev ,这里我下的版本是webpack:^4.43.0 版本

    4. 然后开始进行webpack打包,在项目下建一个index.js 文件。

    1 function fn1(){
    2   alert("hello fn1");
    3 }
    4 fn1()

    5. 执行命令 webpack index.js -o ./dist/bundle.js 将index.js 文件打包到dist文件夹下的bundle.js 文件

    6. 这时就会出现一段警告,让你指定一个mode,只需要创建一个webpack.config.js 文件。里面加上mode就好了

    1 module.exports= {
    2   mode: "development"
    3 }

    7. 再次执行命令 webpack index.js -o ./dist/bundle.js 就会发现生成一个dist 的文件夹,下面有个bundle.js

    8. 进入bundle.js里面,拉到最下面就可以看到bundle 的index.js ,而你写的那段函数也会出现在里面。

    9. 再进行下步,创建一个hello.js 文件,里面同样写上代码(es6语法)

    1 export const fn2 = ()=>{
    2   alert("hello fn2")
    3 }

    10. 在index.js 里面引入hello.js 文件

    1 require("./hello.js");
    2 function fn1(){
    3   alert("hellofn1");
    4 }
    5 fn1()

    11. 再次执行命令webpack index.js  -o ./dist/bundle.js 

    1     Asset      Size  Chunks             Chunk Names
    2 bundle.js  4.67 KiB    main  [emitted]  main
    3 Entrypoint main = bundle.js
    4 [./hello.js] 208 bytes {main} [built]
    5 [./index.js] 228 bytes {main} [built]

    在cmd命令小黑板就会发现新增一行 【./hello.js】信息,同样进入到dist文件夹下的bundle.js 下面也会发现新增 ./hello.js 信息,里面的fn2 也可以看到

    12. 然后index.js 下面引入style.css 文件,我们看下打包的结果

    1 body{
    2   background-color: red;
    3 }
    1 require("./hello.js");
    2 require("./style.css");
    3 function fn1(){
    4   alert("hellofn1");
    5 }
    6 fn1()

    13. 执行webpack index.js -o ./dist/bundle.js ,就会发生错误信息提示,我们需要一个loader来支持这个文件执行

    ERROR in ./style.css 1:4
    Module parse failed: Unexpected token (1:4)
    You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
    > body{
    |   background-color: red;
    | }
     @ ./index.js 9:0-22

    14. 那就下一个loader来试下,css-laoder, cnpm install css-loader --save-dev , 下载完成之后再发现还是报错,这是因为loader没有指定到css文件上,这里加上

    1 require("./hello.js");
    2 require("css-loader!./style.css");
    3 function fn1(){
    4   alert("hellofn1");
    5 }
    6 fn1()

    15. 再次执行命令webpack index.js -o ./dist/bundle.js 就会发现打包成功,在dist文件夹下的bundle.js最下面也会找到style.css的信息

    16. 这时需要在页面验证下打包的结果,新建一个index.html的文件。

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="./dist/bundle.js"></script>
      <title>Document</title>
    </head>
    <body>
      
    </body>
    </html>

    17. 打开页面就会发现只弹出一个 "hellofn1" 的信息,为什么样式没有生效呢!有的人肯定就知道了,这里少了一个loader, style-loader, 执行 cnpm install --save-dev style-loader 

    18. 加到css里面

    1 require("./hello.js");
    2 require("!style-loader!css-loader!./style.css");
    3 function fn1(){
    4   alert("hellofn1");
    5 }
    6 fn1();

    注意style-loader在前面,因为style-loader 会生成<style></style> 样式就会在里面,插入到index.html里面的header中

    19. 再次执行命令 webpack index.js -o ./dist/bundle.js 之后打开页面就会发现先弹框,页面也变成red了。再浏览器的控制面板也可以看到确实是生成了一个style插入到header中,得出结论:css-loader 就是打包.css 的,而style-loader就是生成style,插入到header之中的,这也是为什么style-loader在前,css-loader在后的原因了。

    20.  也可以通过命令行工具指定css的这些loader,执行webpack -h,可以看见我们需要的一些命令

    1 require("./hello.js");
    2 require("./style.css");
    3 function fn1(){
    4   alert("hellofn1");
    5 }
    6 fn1();
      1 Usage: webpack-cli [options]
      2        webpack-cli [options] --entry <entry> --output <output>
      3        webpack-cli [options] <entries...> --output <output>
      4        webpack-cli <command> [options]
      5 
      6 For more information, see https://webpack.js.org/api/cli/.
      7 
      8 Config options:
      9   --config               Path to the config file
     10                          [string] [default: webpack.config.js or webpackfile.js]
     11   --config-register, -r  Preload one or more modules before loading the webpack
     12                          configuration      [array] [default: module id or path]
     13   --config-name          Name of the config to use                      [string]
     14   --env                  Environment passed to the config, when it is a function
     15   --mode                 Enable production optimizations or development hints.
     16                                   [choices: "development", "production", "none"]
     17 
     18 Basic options:
     19   --context    The base directory (absolute path!) for resolving the `entry`
     20                option. If `output.pathinfo` is set, the included pathinfo is
     21                shortened to this directory.
     22                                        [string] [default: The current directory]
     23   --entry      The entry point(s) of the compilation.                   [string]
     24   --no-cache   Disables cached builds                                  [boolean]
     25   --watch, -w  Enter watch mode, which rebuilds on file change.        [boolean]
     26   --debug      Switch loaders to debug mode                            [boolean]
     27   --devtool    A developer tool to enhance debugging.                   [string]
     28   -d           shortcut for --debug --devtool eval-cheap-module-source-map
     29                --output-pathinfo                                       [boolean]
     30   -p           shortcut for --optimize-minimize --define
     31                process.env.NODE_ENV="production"                       [boolean]
     32   --progress   Print compilation progress in percentage                [boolean]
     33 
     34 Module options:
     35   --module-bind       Bind an extension to a loader                     [string]
     36   --module-bind-post  Bind an extension to a post loader                [string]
     37   --module-bind-pre   Bind an extension to a pre loader                 [string]
     38 
     39 Output options:
     40   --output, -o                  The output path and file for compilation assets
     41   --output-path                 The output directory as **absolute path**
     42                                 (required).
     43                                        [string] [default: The current directory]
     44   --output-filename             Specifies the name of each output file on disk.
     45                                 You must **not** specify an absolute path here!
     46                                 The `output.path` option determines the location
     47                                 on disk the files are written to, filename is
     48                                 used solely for naming the individual files.
     49                                                    [string] [default: [name].js]
     50   --output-chunk-filename       The filename of non-entry chunks as relative
     51                                 path inside the `output.path` directory.
     52        [string] [default: filename with [id] instead of [name] or [id] prefixed]
     53   --output-source-map-filename  The filename of the SourceMaps for the
     54                                 JavaScript files. They are inside the
     55                                 `output.path` directory.                [string]
     56   --output-public-path          The `publicPath` specifies the public URL
     57                                 address of the output files when referenced in a
     58                                 browser.                                [string]
     59   --output-jsonp-function       The JSONP function used by webpack for async
     60                                 loading of chunks.                      [string]
     61   --output-pathinfo             Include comments with information about the
     62                                 modules.                               [boolean]
     63   --output-library              Expose the exports of the entry point as library
     64                                                                          [array]
     65   --output-library-target       Type of library
     66          [string] [choices: "var", "assign", "this", "window", "self", "global",
     67       "commonjs", "commonjs2", "commonjs-module", "amd", "umd", "umd2", "jsonp"]
     68 
     69 Advanced options:
     70   --records-input-path       Store compiler state to a json file.       [string]
     71   --records-output-path      Load compiler state from a json file.      [string]
     72   --records-path             Store/Load compiler state from/to a json file. This
     73                              will result in persistent ids of modules and
     74                              chunks. An absolute path is expected. `recordsPath`
     75                              is used for `recordsInputPath` and
     76                              `recordsOutputPath` if they left undefined.[string]
     77   --define                   Define any free var in the bundle          [string]
     78   --target                   Environment to build for                   [string]
     79   --cache                    Cache generated modules and chunks to improve
     80                              performance for multiple incremental builds.
     81                       [boolean] [default: It's enabled by default when watching]
     82   --watch-stdin, --stdin     Stop watching when stdin stream has ended [boolean]
     83   --watch-aggregate-timeout  Delay the rebuilt after the first change. Value is
     84                              a time in ms.                              [number]
     85   --watch-poll               Enable polling mode for watching           [string]
     86   --hot                      Enables Hot Module Replacement            [boolean]
     87   --prefetch                 Prefetch this request (Example: --prefetch
     88                              ./file.js)                                 [string]
     89   --provide                  Provide these modules as free vars in all modules
     90                              (Example: --provide jQuery=jquery)         [string]
     91   --labeled-modules          Enables labeled modules                   [boolean]
     92   --plugin                   Load this plugin                           [string]
     93   --bail                     Report the first error as a hard error instead of
     94                              tolerating it.            [boolean] [default: null]
     95   --profile                  Capture timing information for each module.
     96                                                        [boolean] [default: null]
     97 
     98 Resolving options:
     99   --resolve-alias         Redirect module requests                      [string]
    100   --resolve-extensions    Redirect module requests                       [array]
    101   --resolve-loader-alias  Setup a loader alias for resolving            [string]
    102 
    103 Optimizing options:
    104   --optimize-max-chunks      Try to keep the chunk count below a limit
    105   --optimize-min-chunk-size  Minimal size for the created chunk
    106   --optimize-minimize        Enable minimizing the output. Uses
    107                              optimization.minimizer.                   [boolean]
    108 
    109 Stats options:
    110   --color, --colors               Force colors on the console
    111                                            [boolean] [default: (supports-color)]
    112   --no-color, --no-colors         Force no colors on the console       [boolean]
    113   --sort-modules-by               Sorts the modules list by property in module
    114                                                                         [string]
    115   --sort-chunks-by                Sorts the chunks list by property in chunk
    116                                                                         [string]
    117   --sort-assets-by                Sorts the assets list by property in asset
    118                                                                         [string]
    119   --hide-modules                  Hides info about modules             [boolean]
    120   --display-exclude               Exclude modules in the output         [string]
    121   --display-modules               Display even excluded modules in the output
    122                                                                        [boolean]
    123   --display-max-modules           Sets the maximum number of visible modules in
    124                                   output                                [number]
    125   --display-chunks                Display chunks in the output         [boolean]
    126   --display-entrypoints           Display entry points in the output   [boolean]
    127   --display-origins               Display origins of chunks in the output
    128                                                                        [boolean]
    129   --display-cached                Display also cached modules in the output
    130                                                                        [boolean]
    131   --display-cached-assets         Display also cached assets in the output
    132                                                                        [boolean]
    133   --display-reasons               Display reasons about module inclusion in the
    134                                   output                               [boolean]
    135   --display-depth                 Display distance from entry point for each
    136                                   module                               [boolean]
    137   --display-used-exports          Display information about used exports in
    138                                   modules (Tree Shaking)               [boolean]
    139   --display-provided-exports      Display information about exports provided
    140                                   from modules                         [boolean]
    141   --display-optimization-bailout  Display information about why optimization
    142                                   bailed out for modules               [boolean]
    143   --display-error-details         Display details about errors         [boolean]
    144   --display                       Select display preset
    145               [string] [choices: "", "verbose", "detailed", "normal", "minimal",
    146                                                           "errors-only", "none"]
    147   --verbose                       Show more details                    [boolean]
    148   --info-verbosity                Controls the output of lifecycle messaging
    149                                   e.g. Started watching files...
    150                  [string] [choices: "none", "info", "verbose"] [default: "info"]
    151   --build-delimiter               Display custom text after build output[string]
    152 
    153 Options:
    154   --help, -h     Show help                                             [boolean]
    155   --version, -v  Show version number                                   [boolean]
    156   --silent       Prevent output from being displayed in stdout         [boolean]
    157   --json, -j     Prints the result as JSON.                            [boolean]

    21. 这里需要用到的是--module-bind 参数,然后执行 webpack index.js -o ./dist/bundle.js --module-bind "css=style-loader!css-loader"

    22. 页面一样可以执行,再试下 webpack index.js -o ./dist/bundle.js --module-bind 'css=style-loader!css-loader' --watch,会发现页面一直处于监听状态,代码更新页面也有相应的变化

    23. webpack index.js -o ./dist/bundle.js --module-bind 'css=style-loader!css-loader' --progress   在打包过程中会出现一个进度条展示,打包过程的百分比展示

    24. webpack index.js -o ./dist/bundle.js --module-bind 'css=style-loader!css-loader' --progress --display-modules  可以看见打包的模块展示

    [./hello.js] 208 bytes {main} [built]
    [./index.js] 273 bytes {main} [built]
    [./node_modules/_css-loader@3.5.3@css-loader/dist/cjs.js!./style.css] 287 bytes {main} [built]
    [./node_modules/_css-loader@3.5.3@css-loader/dist/runtime/api.js] 2.46 KiB {main} [built]
    [./node_modules/_style-loader@1.2.1@style-loader/dist/runtime/injectStylesIntoStyleTag.js] 6.64 KiB {main} [built]
    [./style.css] 555 bytes {main} [built]

    25. webpack index.js -o ./dist/bundle.js --module-bind 'css=style-loader!css-loader' --progress --display-modules  --display-reasons 可以看出为什么要打包这个模块的信息

    Hash: e8431bdc67ea088b2267
    Version: webpack 4.43.0
    Time: 441ms
    Built at: 2020-05-24 21:41:34
        Asset      Size  Chunks             Chunk Names
    bundle.js  17.2 KiB    main  [emitted]  main
    Entrypoint main = bundle.js
    [./hello.js] 208 bytes {main} [built]
        cjs require ./hello.js [./index.js] 8:0-21
    [./index.js] 273 bytes {main} [built]
        single entry C:UsersPengDesktopwebpack_yindex.js  main
    [./node_modules/_css-loader@3.5.3@css-loader/dist/cjs.js!./style.css] 287 bytes {main} [built]
        cjs require !!./node_modules/_css-loader@3.5.3@css-loader/dist/cjs.js!./style.css [./style.css] 2:26-106
    [./node_modules/_css-loader@3.5.3@css-loader/dist/runtime/api.js] 2.46 KiB {main} [built]
        cjs require ./node_modules/_css-loader@3.5.3@css-loader/dist/runtime/api.js [./node_modules/_css-loader@3.5.3@css-loader/dist/cjs.js!./style.css] 2:34-108
    [./node_modules/_style-loader@1.2.1@style-loader/dist/runtime/injectStylesIntoStyleTag.js] 6.64 KiB {main} [built]
        cjs require !./node_modules/_style-loader@1.2.1@style-loader/dist/runtime/injectStylesIntoStyleTag.js [./style.css] 1:10-110
    [./style.css] 555 bytes {main} [built]
        cjs require ./style.css [./index.js] 9:0-22

    下次介绍webpack的配置文件!!!!!!!!!!!!!!!!

    转载请注明出处!!

  • 相关阅读:
    PHP+MySQL
    Appstore排名前十的程序员应用软件
    架构师的平凡之路
    程序员,如何三十而立?
    不懂技术也可以轻松开发一款APP
    php语法学习:轻松看懂PHP语言
    你真的了解软件测试行业吗?
    十个程序员必备的网站推荐
    从更高点看软件开发的侧重点
    php如何实现文件下载
  • 原文地址:https://www.cnblogs.com/PengZhao-Mr/p/12952859.html
Copyright © 2011-2022 走看看