preface
Having covered the basics of using Webpack4 in the previous chapter, this section starts building a Vue project in Webpack4 and compares the way it is built with the way it imports vue.js from web script.
Build webpack project development
Start by rebuilding the WebPack project.
Initialize the project file structure
Initialize the package.json file
Package. json uses the stored record NPM to install the relevant package version. Run the following command to initialize:
npm init -y
Copy the code
Execute as follows:
Install webpack
Install the Webpack tool into your local project:
npm i -D webpack webpack-cli
Copy the code
Create and write the configuration file webpack.config.js in the project root directory
const path = require('path');
// This configuration file, which starts as a JS file, exposes a configuration object through module operations in Node
module.exports = {
// In the configuration file, you need to specify the entry and exit manually
entry: path.join(__dirname, './src/main.js'),// entry, indicating which file to pack with WebPack
output: { // Output file related configuration
path: path.join(__dirname, './dist'), // Specify the directory to export the packaged files to
filename: 'bundle.js' // This is the name of the output file}};Copy the code
Normally, the webpack command would do the packing now, but I installed Webpack into my local project above, so I still need to script NPM to execute the internal command.
Execute local Webpack execution commands in package.json configuration
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"."build": "webpack"
},
Copy the code
Now that this is configured, you can use the NPM run script name to execute it as follows:
npm run build
Copy the code
You can see that the bundle.js compressed file has been successfully edited and packaged.
writemain.js
Print the information to set index.html to reference the bundle.js script
First write a printed message in main.js as follows:
console.log("hello world");
Copy the code
Then add bundle.js to index.html as follows:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src=".. /dist/bundle.js"></script>
</body>
</html>
Copy the code
Install Babel
Install Babel into a local project:
npm i -D babel-loader @babel/core
Copy the code
To convert es6 code, install the Babel plug-in:
npm i -D @babel/preset-env @babel/polyfill
Copy the code
Install the Babel plugin to prevent global contamination
npm i -D @babel/plugin-transform-runtime
npm i -S @babel/runtime @babel/runtime-corejs2
Copy the code
Note: Use -d –save-dev to install it into the test development environment, and -s –save to install it into the production environment dependencies.
Create the Babel configuration file in the root directory. Babelrc:
{
"presets": ["@babel/preset-env"]."plugins": [["@babel/plugin-transform-runtime",
{
"corejs": 2."helpers": true."regenerator": true."useESModules": false}]]}"corejs": 2.// Set this to 2 because the version installed above is @babel/runtime-corejs2
Copy the code
Configure webpack.config.js to set the rules for using Babel
module: {
rules: [{test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}}]Copy the code
Write the ES6 syntax in main.js and view the printed information
Before installing Babe to convert ES6\ES7 to less than ES5, I tested it and found that the ES6 syntax works in Chrome, but in Internet Explorer it does not:
The main.js code looks like this:
// ES5
console.log("hello world es5");
// ES6
class Bar {
doStuff() {
console.log('stuff bar'); }}var b = new Bar();
b.doStuff(); // "stuff"
// ES6
class Foo {
static classMethod() {
return 'hello static foo'; }}console.log(Foo.classMethod()); // 'hello'
Copy the code
NPM run build to see if Internet Explorer can print advanced syntax information as follows:
The installationwebpack-dev-server
Install webpack-dev-server to local project:
npm i webpack-dev-server -D
Copy the code
Run the webpack-dev-server command
In package.json script execute the command as follows:
"scripts": {
"dev": "webpack-dev-server"
},
Copy the code
After the server service is started, the input file path is changed to/root
Start the execution service as follows:
npm run dev
Copy the code
Modify theindex.html
The introduction ofbundle.js
And delete from the dist directorybundle.js
file
Go to http://localhost:8080/src/
Common command parameters of webpack-dev-server
"dev": "webpack-dev-server --open --port 3000 --contentBase src --hot"
Copy the code
— open: enable the service to automatically open the browser
–port Port number: specifies the port number used to start the service
ContentBase SRC: Directory in which to start the service setting index.html
–hot: Hot update in patch mode
usehtml-webpack-plugin
Plug-in configuration startup page
Previously, when configuring the use of bundle.js, we stored it in memory and compiled it. Can I also load the index.html page into memory?
Of course, you can use the HTML-wabpack-plugin to do this.
The installationhtml-wabpack-plugin
The plug-in
npm i html-webpack-plugin -D
Copy the code
inwebpack.config.js
Configured in the configuration file
const path = require('path');
// Import a plug-in that generates HTML pages in memory
// All plugins must be placed in plugins
// This plugin has two functions:
// 1\. Automatically generates a memory page based on the specified page in memory
// 2\. Automatically appends the bundled bundle.js to the page
const htmlWebpackPlugin = require('html-webpack-plugin');
// This configuration file, which starts as a JS file, exposes a configuration object through module operations in Node
module.exports = {
// In the configuration file, you need to specify the entry and exit manually
entry: path.join(__dirname, './src/main.js'),// entry, indicating which file to pack with WebPack
output: { // Output file related configuration
path: path.join(__dirname, './dist'), // Specify the directory to export the packaged files to
filename: 'bundle.js' // This is the name of the output file
},
devServer: { // --open --port 3000 --contentBase SRC --hot
open: true.// Automatically open the browser
port: 3000.// Set the port to run on startup
contentBase: 'src'.// Specify the managed root directory
hot: true // Enable hot updates
},
plugins: [ // Configure the node for the plug-in
new htmlWebpackPlugin({ // Create a plug-in that generates HTML pages in memory
template: path.join(__dirname, './src/index.html'), // Specify a template page that will be generated in memory based on the specified page path
filename: 'index.html' // Specify the name of the generated page})].module: {
rules: [{test: /\.js$/, exclude: /node_modules/, loader: "babel-loader"}}};Copy the code
Start the service and find that bundle.js is automatically imported
This plugin does two things:
- Automatically generates an in-memory page based on the specified page
- Automatically appends bundled bundle.js to the page
Use WebPack to package CSS files
The installationstyle-loader css-loader
Tools for processingcss
file
npm i style-loader css-loader -D
Copy the code
inwebpack.config.js
This profile is set to matchcss
Plug-in for file processing
{ test: /\.css$/, use: ['style-loader'.'css-loader']},// Configure third-party loader rules for handling.css files
Copy the code
Use Webpack to pack less files
Install the less-loader less tool to process less files
npm i less-loader less -D
Copy the code
inwebpack.config.js
Configuration file Sets the processing of matching LESS files
{ test: /\.less$/, use: ['style-loader'.'css-loader'.'less-loader']},// Configure the third-party loader rule for processing.less files
Copy the code
Use Webpack to package sass files
Install the sass-loader node-sass tool to process sASS files
cnpm i sass-loader node-sass -D
cnpm i sass fiber -D
Copy the code
inwebpack.config.js
Configuration file sets the processing of matching SCSS files
{ test: /\.scss$/, use: ['style-loader'.'css-loader'.'sass-loader']},// Configure the third-party loader rule for handling.scss files
Copy the code
Use of url-loader in Webpack
Install the url – loader
cnpm i url-loader file-loader -D
Copy the code
inwebpack.config.js
Add loader module to handle URL path:
{ test: /\.(jpg|png|gif|bmp|jpeg)$/, use: 'url-loader? limit=500&name=[hash:8]-[name].[ext]' },
Copy the code
There is another way of entering parameters, in the form of key-value pairs of objects, as follows:
{
test: /\.(jpg|png|gif|bmp|jpeg)$/,
use: [{
loader: 'url-loader'.options: {
limit: 500.// Write a Base64 file whose size is less than 500B to JS
name: '[hash:8]-[name].[ext]' // [hash:8] sets the 8-bit hash before the name, [name] sets the original name of the file, and [ext] sets the original suffix of the file}}},// Loader to process image paths
Copy the code
Distinguish between importing vUE in Webpack and importing VUE using script in regular web pages
With the basic usage components of WebPack built up above, it’s time to start exploring ways to use VUE in WebPack.
So first, let’s review the process of importing Vue using script in ordinary web pages, as follows:
- Import vue packages using script tags
- On the Index page, create a container with the ID app DIV
- Get an instance of the VM with new Vue
With these three steps, we can begin vUE development. But is this true in Webpack?
Install the vue library
First, install the vUE library locally as follows:
cnpm i vue -S
Copy the code
To install vUE into a production dependency, do the following:
Try importing vUE and creating VM in Webpack
1. After the vUE library is installed above, the vUE library is installed belowmain.js
Try importing vue as follows:
/ / import vue
import Vue from 'vue'
Copy the code
2. Create a VM instance
/ / create the vm
var vm = new Vue({
el: '#app'.data: {}});Copy the code
3. Create an app container in index.html
4. Set a MSG value in the VM data and render it in the APP
The main. Js as follows:
Index.html renders the data as follows:
Start the service to check whether the rendering effect is normal, as follows:
vue.runtime.esm.js:620 [Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
Using vue.runtime.esm.js will only build runtime vue code, not compile using templates. Prompts can be returned using the Render method, or built using the built-in compiler.
5. Root causes of the problem:
In webpack, the Vue constructor imported with import Vue from ‘Vue’ is incomplete and only provides runtime-only mode. It does not provide the same use as in web pages.
So if you want to use the web script direct import mode, at this time you need to import the full Vue function JS. So this complete Vue function JS is actually need to find in Nodemodules.
Rules for finding packages:
1. Look for the node_modules folder in the project root directory
2. In node_modules, locate the corresponding vue folder based on the package name
3. In the vue folder, find a package configuration file called package.json
4. In package.json, look for a main property. The main property specifies the entry file to which the package was loaded.
This means that when the library is imported, the file specified by the main attribute is imported.
If you want full functionality, you should import the complete vue.js as follows:
6. Modify the import mode of the VUE library to support complete functions
If you want to modify the js imported into vue, there are two ways:
The first is to modify the imported file directly in the vue library’s package.json file in main.
The second type is the file path directly introduced by hand when importing.
Let’s take a look at the first one, as follows:
The original introduced code
"main": "dist/vue.runtime.common.js"."module": "dist/vue.runtime.esm.js".Copy the code
Instead of
"main": "dist/vue.min.js"."module": "dist/vue.min.js".Copy the code
At this point, when you compile the service again, you can see that the browser is rendering the data properly.
But in general, we don’t change the way the library files. Let’s look at the second one, again before changing the main property of the library file back.
The second way:
After compiling, check whether the rendering data can be viewed as follows:
You can see that you can render data as normal as the introduction of web script.
But if the import vue is written as a path like this:
import Vue from '.. /node_modules/vue/dist/vue.min.js'
Copy the code
It looks very inelegant. Can I still write it
import Vue from 'vue'
Copy the code
But without modifying the main property of the vue library, and can import the actual vue.min.js full function of the script?
Use the resolve attribute to set the import library alias.
In 7.webpack.config.js
addresolve
Properties:
First, change the way the package is imported back as follows:
Add the resolve attribute to webpack.config.js as follows:
resolve: {
alias: {
'vue$': 'vue/dist/vue.min.js'}}Copy the code
Compile and run the service again to verify that the template renders properly, and you can see that it also renders properly.
Summarize the difference between
From the above process, we can find that webpack imports a run-time only incomplete JS by default when importing vue, while we use a regular web page, usually importing a complete VUE library file.
If you need to change the ability to render using templates, you can only change the vue imported file.
Render the specified component into the container with the Render function in vue
Is there a way I can still use the run-time only VUE library and still render components into the APP container?
Of course there is, using the render function.
To demonstrate this, let’s change the alias annotation set above back to use the run-time only library.
Let’s create a Login component and then render it into the container.
1. Create the login component
// Create the login component
var login = {
template: " This is the Login component.
"
};
Copy the code
2. Register the components to the VM in a fully functional way, and then use the components in index. HTML to check whether the components work properly
The component login is registered in main.js
The component login is used in index.html
Start the service and check whether the service is displayed as follows:
3. Write the login component to thelogin.vue
File, then use the render function to render the component
As you saw in the example above, with a run-time only VUE, you can’t use templates to render components directly in the VM. So let’s extract the login component into the login.vue file and use render to return the render Login component. Look at the effect.
3.1 Writing the login.vue file
<template>
<div>
<h1>This is the Login login component</h1>
</div>
</template>
<script>
</script>
<style>
</style>
Copy the code
As you can see, the Vue file is divided into three main parts: template, script, and style
So let’s take a look at what happens if you import it directly as a component.
3.2 Importing the Login component
So let’s start the service and look at the page as follows:
3.3 Installing and compiling plug-ins for vUE files
By default, Webpack does not compile vue files, requiring the installation of plug-ins.
Installation command:
npm i vue-loader vue-template-compiler -D
npm i vue-loader-plugin -S
Copy the code
Execute as follows:
inwebpack.config.js
“, add the followingmodule
Rules:
{ test: /\.vue$/, use: 'vue-loader' }, // Configure processing.vue files
Copy the code
Also configure the plug-in:
// webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
// ...
plugins: [
new VueLoaderPlugin()
]
}
Copy the code
The runtime-only message is displayed as follows:
3.4 Render components using the Render function
// Use the render function to render components
render: function (createElements) {
return createElements(login)
}
Copy the code
The page then looks to see if the component was successfully rendered as follows:
You can see that the component has been successfully rendered.
The render function is abbreviated as follows:
// Use the render function to render components
render: c= > c(login)
Copy the code
conclusion
How to use vUE in Webpack
-
1. Install the vUE package: CNPM I VUE-s
-
2. Since it is recommended to use the.vue component template file to define components in WebPack, you need to install one that can parse this file
npm i vue-loader vue-template-compiler -D
npm i vue-loader-plugin -S
Copy the code
- In 3.
main.js
In the importvue
The moduleimport Vue from 'vue'
- Define one
.vue
The component at the end, where the component consists of three parts:template
script
style
- 5. Use
import login from './login.vue'
Import this component - 6. Create
vm
An instance of thevar vm = new Vue({ el: '#app', render: c => c(login) })
- 7. Create one on the page
id
为app
的div
Elements, as wevm
The region to be controlled by the instance;
For more exciting original Devops articles, please come to my official account: Devops Community: