WEBPACK4 Installation and Learning

Source: Internet
Author: User

In Mu class to learn the Webpack course, made some notes, calculate share is counted. The tutorial is Webpack1 and now the Webpack4 have a lot of differences, they have gone a lot of pits, it is best to use the time to see the official documents.

https://webpack.js.org/in pits also borrowed a lot of people to write articles. So there are many parts of the fusion of super-predecessors of the experience of the summary, and then the actual operation of their own notes. Some places may have the repetition, can understand the good. 1. Global installation webpack       NPM install-g webpack2. Create project files, initialize project files directory   NPM Init to the project file installs webpack   NPM install WEBPACK3. Install the global webpack-cli     NPM install-g webpack-cli //Get the current Webpack version number profile 4. Configuration mode  default to production and development two modes to set command line settings    Webpack-- Mode development5. New entry   New SRC folder under Project Files directory, new Index.js file entry 6. File Packaging    command line input webpack--mode development or Webpack--mode Productionwebpack will be packaged by default, and the./src/index.js file will be packaged as./dist/ Main.js file (auto-Generate Dist folder and Main.js file) 7. Create an HTML file, create an HTML file under the project directory, and refer to the Dist/main.js file directly. Note that the file referenced by our script is dist/main.js, not index.js. This is a trend in front-end development: The source file (Index.js in the example) is differentiated from the final deployed file (Dist/main.js in the example) because the development environment is inconsistent with the user's environment. For example, we can use ES2017 or even ES2018 features in the development environment, and the user's browser is not necessarily supported-this is also the meaning of packaging tools such as Webpack, which can help us build code that works correctly on the target user's browser. 8. Other parameter configurations if you need to configure additional parameters for the Webpack directive, simply add additional parameters after Webpack–mode production/development, such as: Webpack--mode development--watch--progress--display-modules--colors--display-reasons  Real-time Refresh 9. The Monitor file Watch option is most intuitive, but by default, the Watch option is off. Enable watch options     Webpack--mode development--watch10. Refresh the browser (see Official documents Easy pits, how English emmmm)

Https://github.com/webpack/webpack-dev-server

https://webpack.js.org/configuration/dev-server/#devserver

Webpack-dev-server, a EXPRESSJS-based development server, provides the ability to refresh browser pages in real time. Install Webpack-dev-server First install WEBPACK-DEV-SERVER:NPM install-g Webpack-dev-server under the project and then execute Webpack-dev-server--mode under the command line Development--output-public-path Distwebpack-dev-server is a lightweight server that modifies the file source after Auto Refresh page will modify sync to page install Webpack-dev-server:① Global installation: NPM install Webpack-dev-server-g ② installs in the project and writes dependencies in the Package.json file: NPM Install webpack-dev-server--save-dev③ Use command webpack-dev-server --mode development--output-public-path SRC to complete automatic refresh , specify Publicpath, which is easy to refresh without real-time. ④ The default port number is 8080, if 8080 ports need to be occupied, you need to change the port, Webpack-dev-server--port 3000 (the port number is changed to 3000), You can configure the Devserver property directly in the Webpack.config.js configuration file to turn on hot updates and port. ⑤ Start the service, enter the localhost: port number to display all the root directories of the publication, and if there is no index.html file in the project root directory, all the folders in the project root directory are listed in the browser. ⑥ when using webpack-dev-server--mode development --output-public-path src command, each time the file is modified, the file is packaged and stored in memory and is not written on the disk. This packaged file is located at the same level as the index.html in the project root directory. Use the Webpack command to save the packaged file to disk, such as in the Index.html file, by Webpack-dev-server --mode development  -- Output-public-path src packaged build.js<script src= "BuilD.js "></script> introduces Build.js <script src= packaged with webpack command in index.html file"./build/build.js "></script >--inline inline mode to switch between two different modes of the development server. By default, the application will be enabled Inline Mode。 This means that a script will be inserted in the package to handle the real-time reload, and the resulting message will appear in the browser console. --hot Enable hot module replacement//////The above is the search for each tutorial inside said, but the actual operation is still a problem,

The index.html portal file is in the root directory and is not configured content-base because it is configured to only package the configured directory files, which is the root file by default. Publicpath configured with output (it is important that it is not automatically refreshed after it is deleted, it should be webpack-dev-server each package of files according to the output settings generated in the Publicpath directory, and the file itself is still manually packaged, Unable to see automatically refresh packaged files, only configured ports, no configuration Hot:true and Inline:true (the first configuration, but there is an error, so delete the inexplicable OK)

The difference between ⑦webpack's watch command and Webpack-dev-server

--watch is automatically packaged after file modification, Webpack-dev-server is modified and published to the server

⑧webpack-dev-server--mode Development--content-base src--inline--hot//display only for file refresh under SRC path, the browser automatically refreshes after file modification, If the file you want to open and the packaged file is not in a folder, it is best not to set the folder 11. Package CSS files install the loader command line input for processing CSS files under the project directory: NPM install Css-loader Style-loader-- Save-devcss-loader//working with CSS files
Style-loader//Css-loader processed file as style label <style> INSERT into HTML file to specify loader when working with CSS file, as in Index.js file, enter require (' style-loader!css-loader!. /style.css ') or enter Webpack--mode development --module-bind "Css=style-loader!css-loader" 12--progress directly on the command line ( View progress) 13--display-modules (show hidden modules)--display-reasons (show packaging reasons)  15. Configuration, Webpack need to pass in the configuration object, So create a new profile webpack.config.js, or configure it with the node. JS built-in path module and precede it with the __dirname global variable. You can prevent file path problems between different operating systems, and you can make relative paths work as expected. ① first write moudule.exports={}; Configure, ② import file configuration, entry= "portal file path, such as./src/js/main.js"; ③ output file configuration, output={path:__dirname+ "output file path, e.g./ Dist/js/bundle.js "};//to create the Dist folder __dirname the current path to the runtime, and another way to first define the const PATH = require (" path ");// The path module of the Nodejs is then introduced in the output file path Path:path.resolve (__dirname, "./dist/js/bundle.js"), and the//path.resolve () method resolves the current path. Changes the relative path to an absolute path. ④ re-specify the profile name Webpack--config file name such as Webpack--config webpack.dev.config.js16. Define execution scripts that can be set in script in Package.json, such as settings Webpack ":" Webpack--mode development--config webpack.config.js--progress--display-modules--colors--display-reason ",//--colors (ChoiDisplay) directly executes the above script NPM run Webpack17.entry configuration (chunk), ① string representation, single input, all dependencies are specified in the portal file, such as entry: "./src/js/main.js", ② array representation, multiple inputs, Two files that need to be packaged together can be represented in an array in the entry of the configuration file, such as entry:["./app/entry1", "./app/entry2"],//These two files will be packaged together ③ object representation (hash), multi-page entry, entry:{ Page1: "./page1", page2:["./src/a.js", "./src/b.js"}, all three ways to package files in the output file. 18.output configuration, ① a single entry starting point, set an exit, such as Output:{filename: ' Bundle.js ', Path: '/dist/js '}② multiple entry starting points, you can set name or hash, such as output:{ FileName: ' [name].js ', path:__dirname+ '/dist/js '} or Output:{filename: ' [name]-[hash].js ', path:__dirname+ '/dist/js '} or output:{filename: ' [name]-[chunkhash].js ', path:__dirname+ '/dist/js '}hash value can be considered a version number or a MD5 value to guarantee the uniqueness of each file, The hash value of the generated file after each modification is different, and the file name is different. ③publicpath can be understood as placeholders. When you need to go online, you can set the server address to this parameter, Output:{path: ' xxx ', filename: ' xxx ', Publicpath: ' http://cdn.com/'}  plugin (plugin) plugin is Webpack's Pillar function. The webpack itself is built on the same plug-in system used in the Webpack configuration. The plug-in is designed to address other things that loader cannot achieve. 19. Plug-in html-webpack-plugin to be referenced before installing, installing NPM Install Html-webpack-plugin--save-dev installed in the project file directory, References to plug-ins in the Webpack.config.js configuration file var htmlwebpackplugin = require (' HTML-WEBPACk-plugin ');// Commonjs in the Module.exports Add plugin section for plug-in initialization, plug-in list, when multiple bundles need to share some of the same plug-in, Commonchunkplugin can extract these dependencies into a shared package, so as not to repeat. plugins:[    new Webpack.optimize.CommonsChunkPlugin ({        .....     }),    new Htmlchunkplugin ({        Template: ' index.html ',//custom template         filename: ' index-[hash].html ',//Generate file name         inject: ' Head ', Specifies whether the link is injected in the

 

 20.loaderloader allows Webpack to handle non-JavaScript files (Webpack itself only understands JavaScript). Loader can convert all types of files to valid modules that Webpack can handle, and then you can take advantage of Webpack's packaging capabilities to handle them.   Essentially, Webpack loader converts all types of files into modules that can be directly referenced by the application's dependency graph (and the final bundle). Loader can import any type of module. In the Webpack configuration, there are two loader: the ①.test attribute, which is used to represent some or some of the files that should be converted by the corresponding loader. The ②.use property, which indicates that the loader should be used when converting. How to use: ① configuration, specify ② inline in Webpack.config.js, display the specified LOADER③CLI in each import statement, specify   in the shell command Configure loader in Webpack.config.js to add attribute module in module.exports such as install Babel plug-in (JS compiler), use this plugin to convert ES6 code, install according to the official website: module:{     rules:[       {test:/\.js$/,        Exclude:/node_ modules/,        Loader: "Babel-loader"         }   ] Set preset, specify how preset (preconfigured) settings handle the JS file ① set query:{presets:[' latest ']}② in the rules to create a. babelrc file in the root directory with the contents:{    " Presets ": [" env "]}③ in Package.json, add the Babel attribute:" Babel ": {" presets ": [" Latset "]} 21. Optimization can be set in the configuration file, the packaging range, For example, if exclude sets which modules are not processed, the include handles what files are under the content. SpecificYou can view the official documentation for configuration.

Webpack4 Installation and learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.