About webpack

。。 2021-02-23 10:29:38
webpack


Webpack Record documents

  1. Concept : webpack It's a modern JavaScript Static module packager for applications (module bundler). When webpack When processing an application , It recursively builds a dependency graph (dependency graph), It contains each module required by the application , All these modules are then packaged into one or more bundle.
  2. Package the first file :

    • Global installation webpack:

      npm install webpack -g
    • Create a new folder and put in two files , One for html One of them is documents , among HTML Introduce this js The name of the packaged file
    • perform webpack js file The packaged file name
    • At this time, if an error is reported :

      Cannot find module 'webpack-cli'
      Please perform : npm install --save-dev webpack

      Re execution appears :

      WARNING in configuration
      The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
      Please perform npm init -y, Generate package.json
      Building a new webpack.config.js The configuration file , Used for configuration webpack Options
      write in :
      const path = require('path')
      // adopt Node modular , Expose a configuration to the outside
      module.exports = {
      entry:path.join(__dirname, './src/main.js'), // Package files
      output: {
      path: path.join(__dirname, './dist') // Packed file name
      },
      mode: 'development' // Set up mode
      }

      At this point, no error will be reported if the package is executed again , And the generated file will be put into the dist Folder , Default file name main.js

  3. Five core concepts :
    | Chinese name | Configuration item | summary |
    | ---- | ---- | ---- |
    | entrance | entry | The beginning of building dependency graphs |
    | Output | output | Packaging output location |
    | converter | loader | When compiling , For various types of modules , Conversion processing |
    | plug-in unit | plugin | For each task segment , Provide function |
    | Pattern | mode | Set up the packaging environment |
  4. know webpack The configuration file ( namely webpack.config.js)

    • effect : Put the configuration parameters , Extract to a separate file , Easy for project configuration .
    • Basic format :

      const path = require('path') // node The basis of path modular
      const plug-in unit 1 = require(' plug-in unit 1')
      module.exports = {
      // Pattern —— Set the development mode
      mode: 'development',
      // entrance —— Appoint src/index.js Is the entry file
      entry: {
      main: './src/index.js'
      },
      // Output —— Appoint dist/bundle.js Output file for
      output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js'
      },
      // converter . modular > The rules
      module: {
      rules: [
      { test: /\. Suffix name $/,
      use: [
      {
      loader: ' converter 1',
      options: {} // converter 1 To configure
      }
      ]
      }
      ]
      },
      // plug-in unit
      plugins: [
      new plug-in unit 1({
      // The plug-in configuration
      })
      ]
      }
  5. entrance (entry):

    • Every entry attribute , Corresponding to an entry file , Easy to single page 、 Multi page application js introduce ,

       Single page entry
      entry: {
      main: './src/index.js
      }
      // It can be abbreviated as entry: './src/index.js'
       Multi page entry
      entry: {
      one: './src/one/index.js',
      two: './src/two/index.js',
      three: './src/three/index.js'
      }

    You can also use node Of path Module implementation gets the path relative to the configuration file

     const path = require('path')
    module.exports = {
    entry: path.resolve(__dirname, './app.js')
    }
    // Be careful , there __dirname, For two underscores 
    • entry Three formats are supported :

      object :

      entry: {
      <key>: <value>
      }
      // key It can be a simple string , Corresponding output.filename The configuration of the [name] Variable ,
      entry: {
      'app-entry': './app.js'
      }
      // key It can also be a path string . here webpack The path directory will be generated automatically , And take the end of the path as [name]
      entry: {
      'path/of/entry': './app.js'
      }
      // value If it's a string , And it has to be reasonable noderequire Function parameter string . For example, file path :'./app.js'(require('./app.js')); For example, installed npm modular :'lodash'(require('lodash'))
      entry: {
      'my-lodash': 'lodash'
      },
      output: {
      path: './output',
      filename: '[name].js'
      }

      Array :

      entry: ['./app.js', 'lodash']
      Equivalent to :
      entry: {
      main: ['./app.js', 'lodash']
      }

      character string :

      entry: './app.js'
      Equivalent to
      entry: {
      main: './app.js'
      }
  6. output( Output )

    • output Is an option that affects the compilation output .output Options tell webpack How to write the compiled file to disk . Be careful , Although there can be many inputs , But there is only one output configuration

      output: {
      path: path.resolve(__dirname, 'dist')
      filename: [name].js // Use [name] Place holder , Automatically identify the entry file name , So as to distinguish the package file name
      }
    • output.filename: Specifies the file name of the file to output to the hard disk . This can't be an absolute path !output.path Will determine the existence path of the file .filename Just to name each file .

      [name] Replaced by the name of the entry .

      [hash] By compiler hash Replace .

      [chunkhash] Imported hash Replace .

    • output.path Compiled file storage path , Absolute path , take [hash] The file that will be compiled hash Replace
    • output.chunkFilename Non entrance chunk The name of the file , As a relative path to output.path in .
  7. module Configure how to handle modules

    • rules Configure the reading and parsing rules of the module , Usually used to configure Loader, A type is an array , Each item in the array describes how to handle a particular file .

    Matching rules :

    1. Matching conditions : adopt test/include/exclude Three configuration items to hit Loader The rule file to apply
    2. Application rules : For the selected file through use Configure items to apply loader, You can apply a loader Or apply a set from the back to the front loader, At the same time, we can give loader Pass in the parameter .
    3. Reset order , A group of loader The default execution order is from right to left , adopt exforce Option to make one of loader The order of execution is placed first or last .
    module: {
    rules: [
    {
    test: /\.js$/,
    use: ['babel-loader?cacheDirectory'],
    include: path.resolve(__dirname, 'src')
    },
    {
    test: /\.scss$/,
    use: ['style-loader', 'css-loader', 'sass-loader'],
    exclude: path.resolve(__dirname, 'node_modules')
    },
    { // test、include、exclude Array types are also supported
    test: [/\.jsx?$/, /\.tsx?$/],
    include: [
    path.resolve(__dirname, 'src'),
    path.resolve(__dirname, 'test')
    ],
    exclude: [
    path.resolve(__dirname, 'node_modules'),
    path.resolve(__dirname, 'bower_modules')
    ]
    }
    ]
    }
    
    • stay loader When you need to pass in a lot of parameters , We can also pass a object To describe , Such as :

      use: [
      {
      loader: 'babel-loader',
      options: {
      cacheDirectory: true
      },
      // enforce:'post' It means to put the Loader The order of execution is put at the end of
      // enforce The value of can also be pre, Delegate Loader The order of execution is put first
      enforce:'post'
      }
      ]
    • noParse: It can make webpack Ignore the recursive parsing and processing of some files that are not modularized , The type can be RegExp, [RegExp], function One of them
    • common loader To configure :

      { // Load image
      test: /\.(png|svg|jpg|gif)$/,
      use: [
      'file-loader'
      ]
      }
      { // Load Fonts
      test: /\.(woff|woff2|eot|ttf|otf)$/,
      use: [
      'file-loader'
      ]
      }
      { // load css
      test: /\.css$/,
      use: [
      'style-loader',
      'css-loader'
      ]
      }
      
  8. plugins:

    // adopt new example , To enable the plugin
    plugins: [
    new webpack.ProgressPlugin(), //webpack Comes with a series of plug-ins
    new HtmlWebpackPlugin({template: './src/index.html'}) // Use object , Configure parameters for plug-ins
    ]

    common plugin:

    • HotModuleReplacementPlugin – Turn on global module hot swap (HMR);
    • NamedModulesPlugin – When modules are hot swapped (HMR) Output more user-friendly module name information in the browser console ;
    • CommonsChunkPlugin – extract chunk Common part ;
    • ExtractTextPlugin – Independent generation css file , Load in the form of outer chain ;
    • UglifyJsPlugin – Compress js;
    • HtmlWebpackPlugin – Use templates to generate html.
  9. environment variable :

    webpack You can set environment variables to distinguish between production mode and development mode , Different operations are performed from this .

    const NODE_ENV = process.env.NODE_ENV // You can get environment variables
    It can be concluded that the current production mode or development mode 
  10. Development mode :webpack.dev.js The configuration file
  11. Production mode :webpack.prod.js The configuration file
  12. resolve: webpack When building the package, you will search the files according to the directory ,resolve Attribute extensions Array used to configure which file suffixes can be completed by the program itself . for example :

    resolve: {
    nodules: [path.resolve(__dirname, "node_modules")],
    extensions: ['.js', '.json', '.scss', '.vue', '.json']
    // Module alias definition , Refer to alias directly after convenience , No need to write long address
    alias: {
    '@/static': resolve('static'), // take @/static Point to the current project , Under the static Catalog
    '@': resolve('src'), // take @ Point to src Catalog
    }
    }
  13. command :

    // Development mode , Start the server
    webpack-dev-server --open --config webpack.dev.js
    // Production mode , pack
    webpack --config webpack.prod.js
  14. webpack It can also support Node operation , It can be done by Node Operate on existing files , To meet the needs of packaging .

Use demo Reference resources : Ruan Yifeng's https://github.com/ruanyf/web...

版权声明
本文为[。。]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/02/20210223102604943X.html

  1. Svg editor -- new path
  2. Detailed explanation of debounce and throttle of JavaScript function
  3. Anti shake and throttling and corresponding react hooks package
  4. C2m: the first CSDN article moved to MOOC script 5000 words, detailed painstaking development process, there are renderings and source code at the end of the article
  5. Front end, school recruitment, Taobao, guide
  6. [vue2 & G6] get started quickly
  7. Canvas from the beginning to the pig
  8. Take five minutes to standardize the code comments?
  9. Some thoughts on sass
  10. what?! You haven't filled in the award information yet
  11. How to get the interface + tsdoc needed by TS through swagger
  12. Binary tree
  13. Canvas drawing method in Web screenshot
  14. Front end docker image volume optimization (node + nginx / node + multi-stage construction)
  15. Become a big influence of technology? Coding pages quickly build personal blog
  16. Object and array deconstruction, spread operator, rest operator
  17. Analysis of Axios source code
  18. Two ways to delete useless code in project (Practical)
  19. Edit your picture with canvas
  20. Today's chat: 2-4 years to walk out of the resignation dilemma and comfort zone
  21. JS mechanism 3: stack, heap, garbage collection
  22. [grid compression evaluation] meshquan, meshopt, Draco
  23. Deep understanding of Vue modifier sync [Vue sync modifier example]
  24. WebView for front end engineers
  25. React form source code reading notes
  26. Deep thinking about modern package manager -- why do I recommend pnpm instead of NPM / yarn?
  27. On the sequence of event capture and event bubbling
  28. Help you build a systematic understanding of the front end scaffolding
  29. commander.js Principle analysis
  30. Common usage of nginx
  31. H5 jump to wechat app
  32. Front end algorithm interview must brush questions series [14]
  33. Thinking of cross end practice
  34. Vue server rendering principle analysis and introduction
  35. [KT] vscode plug in development example series (2)
  36. Design ideas of react and Vue framework
  37. JavaScript String.prototype.replaceAll 兼容性导致的问题
  38. JavaScript String.prototype.replaceAll Problems caused by compatibility
  39. 爱奇艺体育:体验Serverless极致扩缩容,资源利用率提升40%
  40. Iqiyi Sports: experience the ultimate expansion and contraction of serverless, and increase the utilization rate of resources by 40%
  41. 对前端异常window error捕获的全面总结
  42. A comprehensive summary of front end exception window error capture
  43. 成功解决Problem while trying to mount target]\“. HTTP response code is 400
  44. Problem while trying to mount target] \ ". HTTP response code is 400
  45. 放弃okhttp、httpClient,选择了这个牛逼的神仙工具!贼爽
  46. 前端面试每日 3+1 —— 第679天
  47. How to add elements at the beginning of an array in JS?
  48. Give up okhttp and httpclient and choose this awesome immortal tool! Thief Shuang
  49. Front end interview daily 3 + 1 - day 679
  50. 【2021 第一期】日常开发 26 个常见的 JavaScript 代码优化方案
  51. Daily development of 26 common JavaScript code optimization schemes
  52. 前端的字符串时间如何自动转换为后端Java的Date属性,介绍springMVC中如何解决时间转换问题
  53. How to automatically convert the front-end string time to the back-end Java date attribute, and how to solve the time conversion problem in spring MVC are introduced
  54. 前端面试常考题:JS垃圾回收机制
  55. ReactDOM.render串联渲染链路(一)
  56. 更简洁、更快速!腾讯云 Serverless 云函数创建流程再次升级!
  57. 粗涉Webpack
  58. Frequently asked questions in front end interview: JS garbage collection mechanism
  59. ReactDOM.render Serial rendering link (1)
  60. More concise and faster! Tencent cloud serverless cloud function creation process upgrade again!