Vue bucket -- 11 Webpack and Vue loader package resources
11.1 Webpack introduction
11.1.1 what is webpack
Webpack is a front-end static module resource packaging tool, which enables browsers to support modularization. It will be statically divided according to the dependency of the module
Then these modules generate corresponding static resources according to the specified rules.
11.1.2 Webpack function
**The Webpack core is mainly used to package JavaScript resources
**As shown in the figure below, it can combine with other plug-in tools to convert the classification of various static resources css, png and sass into static files, which can reduce
Fewer page requests.
**The babel tool can be integrated to realize EcmaScript 6 to EcmaScript 5, so as to solve the compatibility problem
**Integrated http server
**It can integrate the functions of module hot loading, automatically refreshing the browser when the code changes, etc
11.1.3 references
The versions of webpack1 and webpack2 + have changed a lot, and they are basically pushed over and over again. Webpack1 is basically not used at present.
**webpack1 official website https://webpack.github.io/
**webpack2.x English official website https://webpack.js.org/
**webpack2.x Chinese official website https://webpack.docschina.org/
**webpack2.x guide document: https://webpack.docschina.org/guides/
11.2 Webpack installation and cases
11.2.1 global installation
1. Install webpack
Install the latest version npm install --global webpack Or install a specific version npm install --global webpack@<version>
2. If the webpack v4 + version is installed above, you need to install the CLI before using the webpack command line
npm install --1 global webpack-cli
npm install --1 global webpack-cli
3. If the webpack command in the command line window is unavailable after installation, manually configure the environment variable of the global directory
11.2.2 quick start
Install the plug-in Node Snippets in VSCode, and there is a code shortcut prompt
(1) Package JS module
1.1 global installation webpack@v4.35.2 And webpack-cli@3.3.6
npm i -g webpack@v4.35.2
npm i -g webpack-cli@3.3.6
1.2 check the version number after installation. If there is a red word reminder, it's OK to ignore it
webpack -v
1.3 if the webpack command in the command line window is not available after installation, configure the environment variable
Reference website: https://www.cnblogs.com/steamed-twisted-roll/p/11299429.html
1.4 create the following directory structure and files
webpack-demo1 |— index.html |— js |- bar.js |— main.js
1.5 bar.js
// node Modular programming, derived function module.exports = function () { console.log('I am bar modular') }
1.6 main.js
var bar = require('./bar') // Can be omitted .js Suffix bar() // call bar.js Functions in
1.7 run the js module on node. Note the directory where the command is executed: WebStudy\webpack-demo1
1.8. The index.html file introduces main.js as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script src="./js/main.js"></script> </body> </html>
1.9 when accessing index.html, the browser cannot recognize the JS modular file
**Node execution is possible
1.10 package JS. Pay attention to the directory where the command is executed: WebStudy\webpack-demo1. Do not lose - o
Command: webpack module entry file path - o module exit file path
one point one one Change the JS file introduced by index.html into a JS target file that can be recognized by the browser after packaging
<body> <script src="./js/bundle.js"></script> </body>
1.12 normal output
(2) Transform directory structure
(3) Packaging configuration file webpack.config.js
// quote Node.js Medium path Module, a gadget that handles file paths const path = require("path"); // 1. Export a webpack Objects with special property configurations module.exports = { // Specify mode configuration,Value: none(Nothing), development or production(default) // For example, production After mode packaging bundle.js It's a compressed version, development Is not compressed mode:'none', // entrance entry: './src/main.js', // Entry module file path // Exports are objects output: { // path Must be an absolute path , __dirname Is current js Absolute path to: //D: \StudentProject\WebStudy\webpack- demo2 path: path.join(__dirname, './dist/'), // Packaged result file storage directory filename: 'bundle.js' // Packaged result file name } }
11.2.3 summary of global installation
Global installation of webpack is not recommended. The globally installed webpack uses the one you installed on your computer when packaging the project
Webpack, if the project is on another person's computer, he may install an old version of webpack. Then compatibility may be involved. and
And if it does not install webpack globally, it cannot be packaged.
Therefore, in order to solve the above problems, the official recommends installing webpack locally, that is, installing webpack into the corresponding project. Where does this project go,
The webpack follows wherever it goes (the webpack packaging tool follows the project).
11.2.4 local installation (recommended)
During local installation, it is recommended to install webpack into devdependences development dependency (- - save DEV), because webpack is only a packaging tool. If the project needs to be online, it is the packaging result instead of this tool.
Therefore, in order to distinguish between production environment and development environment dependencies, we distinguish them by -- save (production environment) and -- save dev (development environment).
Local installation command
Install the latest version npm install --save-dev webpack Install a specific version npm install --save-dev webpack@<version>
Demo:
a. First uninstall the globally installed webpack and webpack cli
npm uninstall -g webpack
npm uninstall -g webpack-cli
b. Installation webpack@v4.35.2 With webpack cli
# 1. Enter webpack-demo3 cd d:\StudentProject\WebStudy\webpack-demo3 # 2. Initialize project `-y` Yes, the default configuration is adopted npm init -y # 3. install v4.35.2 ,No less v npm i -D webpack@v4.35.2 # Installing the CLI npm i -D webpack-cli@3.3.6
c. In the locally installed webpack, you need to configure the scripts command mapping in the package.json file under the project folder
"scripts": { "show": "webpack -v", "start": "node ./src/main.js", "build": "webpack" },
d. Then execute the corresponding command through the npm run command alias
npm run show
npm run build
npm run start
npm start
11.3 EcmaScript 6 module specification
export module (equivalent to module.exports)
Import module import (equivalent to require)
ES6 reference documents: https://es6.ruanyifeng.com/
11.3.1 exporting default members
Syntax: there can only be one member by default, otherwise an error will be reported
export default member
// derived function /* module.exports = function () { console.log('I am bar module -- -- Node ') } */ // ES6 , Export a default member(Any type),One js Only one of the default. Members of any type can be exported by default /* export default function (){ console.log('I am bar module -- -- ES6 ') } */ // export default 'hello' export default { name: 'mxg' }
11.3.2 importing default members
import xxx from Module file
// Node Import module // var bar = require('./bar') // bar() // ES6 Import // The default load is export default member import bar from './bar' // bar() // console.log( bar )
11.3.3 exporting non default members
Syntax: a non default member must have a member name
export member
export const x = 'xxx'; export const y = 'yyy'; export function add(a, b) { return (a - 0) + (b - 0); }
Error message:
//No variable name, wrong export 'xxx' // No function name, wrong export function (a, b) { return a + b }
11.3.4 importing non default members
// Method 1: import the specified members on demand and use the method of deconstruction and assignment import {Member name 1, Member name 2, ..., member name n} from Module file // Method 2: import all members in the module file at one time (including default (member) import * as alias from Module file
// adopt export xxx The exported non default members can be loaded on demand by deconstruction assignment // x The correspondence is bar.js Medium x Members, y The correspondence is bar.js Medium y Members, import {x, y, add} from './bar' console.log(x, y, add(10, 20)) // One time loading export xxx Export all members, Deconstruction assignment is not used import * as bar2 from './bar' console.log(bar2)
11.4 package CSS/Images and other resources
11.4.1 packaging CSS resources
(1) Installing style loader and CSS loader dependencies
css loader loads css into javascript;
Style loader is to let javascript know css.
npm install --save-dev style-loader css-loader
(2) Modify the webpack.config.js file
// quote Node.js Medium path Module, a gadget that handles file paths const path = require("path"); // 1. Export a webpack Objects with special property configurations module.exports = { // Specify mode configuration,Value: none(Nothing), development or production(default) // For example, production After mode packaging bundle.js It's a compressed version, development Is not compressed mode: 'none', // entrance entry: './src/main.js', // Entry module file path // Exports are objects output: { // path Must be an absolute path , __dirname Is current js Absolute path to: //D: \StudentProject\WebStudy\webpack- demo2 path: path.join(__dirname, './dist/'), // Packaged result file storage directory filename: 'bundle.js' // Packaged result file name }, module: { // modular rules: [ // rule { test: /\.css$/, // Regular expressions, matching. css file resources use: [ // The Loader used shall be in the correct order 'style-loader', 'css-loader' ] } ] } }
(3) Create a CSS folder in the src folder, and create style.css under the CSS folder
body { background-color: cadetblue; }
(4) Only style.css is introduced in main.js
import './css/style.css'
(5) Repackage and compile, and index.html shows the above effect!
npm run build
****Principle:
F12 after viewing the source code of index.html, the CSS file content is actually converted into a JavaScript module. Then, when running JavaScript, the style will be dynamically used under the page < head > tag
11.4.2 packaging Images resources
(1) Install file loader dependency
npm install --save-dev file-loader
(2) Modify webpack.config.js
// quote Node.js Medium path Module, a gadget that handles file paths const path = require("path"); // 1. Export a webpack Objects with special property configurations module.exports = { // Specify mode configuration,Value: none(Nothing), development or production(default) // For example, production After mode packaging bundle.js It's a compressed version, development Is not compressed mode: 'none', // entrance entry: './src/main.js', // Entry module file path // Exports are objects output: { // path Must be an absolute path , __dirname Is current js Absolute path to: //D: \StudentProject\WebStudy\webpack- demo2 path: path.join(__dirname, './dist/'), // Packaged result file storage directory filename: 'bundle.js' // Packaged result file name }, module: { // modular rules: [ // rule { test: /\.css$/, // Regular expressions, matching .css File resources use: [ // Used Loader ,Note that the order cannot be wrong 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] } ] } }
(3) Package compilation
Note:
If you directly access index.html in the root directory, the image resource path cannot be accessed.
Solution: put index.html in dist directory.
However, dist is the result of package compilation, not the source code, so it is inappropriate to put index.html in dist.
Moreover, once we change the package result file name bundle.js, index.html should also be modified manually.
To solve the above problems, you can use a plug-in: HTML webpack plugin
11.4.3 html-webpack-plugin
Install plug-ins
npm install --save-dev html-webpack-plugin
Modify webpack.config.js
// quote Node.js Medium path Module, a gadget that handles file paths const path = require("path"); // Introducing plug-ins const HtmlWebpackPlugin = require('html-webpack-plugin'); // 1. Export a webpack Objects with special property configurations module.exports = { // Specify mode configuration,Value: none(Nothing), development or production(default) // For example, production After mode packaging bundle.js It's a compressed version, development Is not compressed mode: 'none', // entrance entry: './src/main.js', // Entry module file path // Exports are objects output: { // path Must be an absolute path , __dirname Is current js Absolute path to: //D: \StudentProject\WebStudy\webpack- demo2 path: path.join(__dirname, './dist/'), // Packaged result file storage directory filename: 'bundle.js' // Packaged result file name }, module: { // modular rules: [ // rule { test: /\.css$/, // Regular expressions, matching .css File resources use: [ // Used Loader ,Note that the order cannot be wrong 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] } ] }, // Configure plug-ins plugins: [ new HtmlWebpackPlugin({ // This plug-in is used to package index.html into the directory of bundle.js, // At the same time, bundle.js will be automatically introduced into < script > in index.html // Note: the file name bundle depends on the name specified in output.filename above template: './index.html' }) ] }
Package and compile. index.html is available in dist folder. The access is normal!
11.5 real time reload
11.5.1 description
Adopt the tool provided by webpack: webpack dev server, which allows all types of modules to be updated at runtime without manual typing
Package and refresh page will automatically package and refresh the page. It can greatly improve the development efficiency.
reference resources: https://webpack.docschina.org/guides/development/# Use - webpack dev server
11.5.2 practical operation
Installation dependency
npm install --save-dev webpack-dev-server
Modify webpack.config.js configuration
// quote Node.js Medium path Module, a gadget that handles file paths const path = require("path"); // Introducing plug-ins const HtmlWebpackPlugin = require('html-webpack-plugin'); // 1. Export a webpack Objects with special property configurations module.exports = { // Specify mode configuration,Value: none(Nothing), development or production(default) // For example, production After mode packaging bundle.js It's a compressed version, development Is not compressed mode: 'none', // entrance entry: './src/main.js', // Entry module file path // Exports are objects output: { // path Must be an absolute path , __dirname Is current js Absolute path to: //D: \StudentProject\WebStudy\webpack- demo2 path: path.join(__dirname, './dist/'), // Packaged result file storage directory filename: 'bundle.js' // Packaged result file name }, module: { // modular rules: [ // rule { test: /\.css$/, // Regular expressions, matching .css File resources use: [ // Used Loader ,Note that the order cannot be wrong 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] } ] }, // Configure plug-ins plugins: [ new HtmlWebpackPlugin({ // The purpose of this plug-in is to index.html Pack to bundle.js In the directory, // At the same time index.html Automatic in <script> introduce bundle.js // Note: the file name bundle Depends on the above output.filename Name specified in template: './index.html' }) ], // Real time reload devServer: { contentBase: './dist'//Configure packaged destination path } }
Modify the scripts of package.json -- the open option is packaged successfully, and the browser will be opened automatically
"dev": "webpack-dev-server --open"
Then npm run dev is executed, and it's OK
11.6 Babel browser compatibility
11.6.1 installing Bable
npm install -D babel-loader @babel/core @babel/preset-env
11.6.2 configuring webpack.config.js
// quote Node.js Medium path Module, a gadget that handles file paths const path = require("path"); // Introducing plug-ins const HtmlWebpackPlugin = require('html-webpack-plugin'); // 1. Export a webpack Objects with special property configurations module.exports = { // Specify mode configuration,Value: none(Nothing), development or production(default) // For example, production After mode packaging bundle.js It's a compressed version, development Is not compressed mode: 'none', // entrance entry: './src/main.js', // Entry module file path // Exports are objects output: { // path Must be an absolute path , __dirname Is current js Absolute path to: //D: \StudentProject\WebStudy\webpack- demo2 path: path.join(__dirname, './dist/'), // Packaged result file storage directory filename: 'bundle.js' // Packaged result file name }, module: { // modular rules: [ // rule { test: /\.css$/, // Regular expressions, matching .css File resources use: [ // Used Loader ,Note that the order cannot be wrong 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, // Excluded directories use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] // Built in translation tools } } } ] }, // Configure plug-ins plugins: [ new HtmlWebpackPlugin({ // The purpose of this plug-in is to index.html Pack to bundle.js In the directory, // At the same time index.html Automatic in <script> introduce bundle.js // Note: the file name bundle Depends on the above output.filename Name specified in template: './index.html' }) ], // Real time reload devServer: { contentBase: './dist'//Configure packaged destination path } }
11.7 Vue loader packaging Vue single file components
11.7.1 basic configuration of packaged Vue
Install Vue loader and Vue template compiler dependencies
npm install -D vue-loader vue-template-compiler
Modify webpack.config.js configuration
1. Declaration plug-in
const VueLoaderPlugin = require('vue-loader/lib/plugin');
2. Module rules, configure Vue loader
{ test: /\.vue$/, loader:'vue-loader' }
3. Configure plug-ins
new VueLoaderPlugin()
// quote Node.js Medium path Module, a gadget that handles file paths const path = require("path"); // Introducing plug-ins const HtmlWebpackPlugin = require('html-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); // 1. Export a webpack Objects with special property configurations module.exports = { // Specify mode configuration,Value: none(Nothing), development or production(default) // For example, production After mode packaging bundle.js It's a compressed version, development Is not compressed mode: 'none', // entrance entry: './src/main.js', // Entry module file path // Exports are objects output: { // path Must be an absolute path , __dirname Is current js Absolute path to: //D: \StudentProject\WebStudy\webpack- demo2 path: path.join(__dirname, './dist/'), // Packaged result file storage directory filename: 'bundle.js' // Packaged result file name }, module: { // modular rules: [ // rule { test: /\.css$/, // Regular expressions, matching .css File resources use: [ // Used Loader ,Note that the order cannot be wrong 'style-loader', 'css-loader' ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }, { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, // Excluded directories use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] // Built in translation tools } } },{ test: /\.vue$/, loader:'vue-loader' } ] }, // Configure plug-ins plugins: [ new HtmlWebpackPlugin({ // The purpose of this plug-in is to index.html Pack to bundle.js In the directory, // At the same time index.html Automatic in <script> introduce bundle.js // Note: the file name bundle Depends on the above output.filename Name specified in template: './index.html' }), new VueLoaderPlugin() ], // Real time reload devServer: { contentBase: './dist'//Configure packaged destination path } }
11.7.2 webpack and Vue single file component cases
directory structure
Installing vue module
npm i vue
index.html single page entry
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <!-- 1. vue entrance --> <div id="app"></div> </body> </html>
App.vue root component
<template> <div> <h1>App Root component</h1> <h2>{{ msg }}</h2> <!-- <Foo/> --> <foo></foo> <bar></bar> </div> </template> <script> // To use a component, you must import it before using it import Foo from './components/Foo.vue' import Bar from './components/Bar.vue' // Export a default member object, which is the current component object and can be used directly in the object Vue Options in, such as data/methods/watch export default { data () { return { msg : 'hello mxg' } }, // template: This option does not need to be written because the above template The tag represents the current component template // Reference sub component components: { Foo, Bar } } </script> <style scoped> /* scoped The function is to apply the style only to the current component, otherwise it will be passed to other parent and child components */ h1 { color: red } </style>
main.js package entry file
import Vue from 'vue' import App from './App.vue' new Vue({ el: '#app', template: '<App />', components: {App} })
Package build
npm run build
11.7.3 resolve warning issues
// Introduced in this way vue Module, whether it corresponds to the full version (compilation function, operation function) // It is imported by default vue In the module package.json in main The one introduced in the option"main": "dist/vue.runtime.common.js" // By default, the running version is introduced, and there is no compilation function, so a warning will be issued // import Vue from 'vue' // Solution: manually import the specified version, and the full version is imported on the front // import Vue from 'vue/dist/vue.js' // Mode 2: adopt webpack Configure full version vue.js import Vue from 'vue' import App from './App.vue' /* new Vue({ el: '#app', // template In essence, there is no compilation and rendering function, but the current compilation function can be compiled directly by Vue loader, // The rendering function is essentially to render components through the render function, so you only need to specify the render component here // template: '<App />', // <App></App> // render: function (h) { // h It is a function for the component to receive the rendering // return h(App) //The return value of the function is the result of rendering // }, // If render is used for rendering, the components in main.js can be omitted // components: {App} // Arrow function abbreviation 1 // render: h => { // return h(App) // } // Arrow function abbreviation 2 render: h => h(App) }) */ new Vue({ render: h => h(App) }).$mount('#app')
11.7.4. Vue single document component full version
App.vue
<template> <div> <h1>App Root component</h1> <h2>{{ msg }}</h2> <!-- <Foo/> --> <foo></foo> <bar></bar> </div> </template> <script> // To use a component, you must import it before using it import Foo from './components/Foo.vue' import Bar from './components/Bar.vue' // Export a default member object, which is the current component object and can be used directly in the object Vue Options in, such as data/methods/watch export default { data () { return { msg : 'hello mxg' } }, // template: This option does not need to be written because the above template The tag represents the current component template // Reference sub component components: { Foo, Bar } } </script> <style scoped> /* scoped The function is to apply the style only to the current component, otherwise it will be passed to other parent and child components */ h1 { color: red } </style>
Foo.vue
<template> <!-- One vue There is one and only one in the file template --> <div> <h1>I am Foo Sub assembly 1111</h1> <h2>I am Foo Subcomponents h22222</h2> </div> </template> <script> // If you don't write js code,Yes, No <script> // The general method is to export a default member object export default { } </script> <style scoped> /* If you don't write style code, you don't need < style > */ /* scoped The function is to apply the style only to the current component, otherwise it will be passed to other parent and child components */ h2 { color: blue } </style>
11.7.5 module hot replacement (HMR)
// introduce node Medium path Module, a gadget that handles file paths const path = require('path') // Introducing plug-ins const HtmlWebpackPlugin = require('html-webpack-plugin') // 1. introduce vue-loader plug-in unit const VueLoaderPlugin = require('vue-loader/lib/plugin') // 1. Import webapck and load the thermal module const webpack = require('webpack') // Export a webpack Objects with special property configurations module.exports = { mode: 'none', // Specify mode configuration:"development" | "production" | "none" // entrance entry: './src/main.js', // Entry module file path // Export output: { // path: './dist/', Error, specify the absolute path path: path.join(__dirname, './dist/'), //The directory generated by the packaged result file must be an absolute path filename: 'bundle.js' }, // Configure plug-ins plugins: [ new HtmlWebpackPlugin({ // Specify the template page to package // Will index.html Package to and bundle.js Under the same directory, // At the same time index.html It will be used automatically in script Label introduction bundle.js template: './index.html' }), // 3. Please make sure to introduce this plug-in! new VueLoaderPlugin(), // 3. Configure hot module loading object new webpack.HotModuleReplacementPlugin() ], // Real time reload devServer: { // Target path contentBase: './dist', // 2. Turn on the thermal module loading, hot: true }, module: { rules: [ //Configure conversion rules { test: /\.css$/, // Note that there are no single quotes, regular expressions, or matches .css File resources use: [ // According to the habits of foreigners, and don't write the order wrong 'style-loader', // js distinguish css 'css-loader' // css Convert to js ] }, { test: /\.(png|svg|jpg|gif)$/, use: [ 'file-loader' ] }, // Resolve compatibility issues { test: /\.m?js$/, exclude: /(node_modules)/, // Excluded directories use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] // babel Conversion rule tool for content in } } }, // 2. handle .vue Single file component { test: /\.vue$/, loader: 'vue-loader' } ] }, // Parse full version vue.js // resolve: { // alias: { // 'vue$': 'vue/dist/vue.js' // } // } }