Use Webpack to package, configure and load VUE components

webpack4 make sure to use Node version> = 8.9.4

Webpck is a front-end resource loading / packing tool. It performs static analysis based on the module's dependencies, and then generates corresponding static resources according to the specified rules for these modules.
Official website: https://webpack.js.org/

Using webpack4 no longer requires webpack.congig.js as the package entry configuration file.
The default entry is the index of './src' and the default exit of './dist', small projects can be applied, large projects are not recommended.

ps: when installing the package I am using is cnpmnot npmbecause Taobao mirror, to see if the students do not have this article can be removed from the c.

1-10 is the basic configuration of webpack. 11-12 is the configuration and packaging of vue components

  1. Create project –
  2. Install and configure webpack –
  3. Modify packaged entrance and exit –
  4. Configure the automatic packaging function –
  5. Configure html-webpack-plugin to generate preview page –
  6. Configure the relevant parameters for automatic packaging –
  7. Webpack's loader is basically used –
  8. Configure postCSS to automatically add css compatible prefixes –
  9. Pack the pictures and font files in the style sheet –
  10. (babel) Pack and process advanced syntax in js file –
  11. Configure vue component loader –
  12. webpack packaging –

> 1. Basic usage of webpack

  1. Create a blank project directory, and run the npm init -ycommand, initialization packet management configuration file package.json
  2. New src source code directory
  3. New src-> index.html home page
  4. Initialize the basic structure of the home page
  5. Run npm install jquery -scommand to install jquery
  6. Through the modular form, realize the function
    index.html content
    of interlacing the color of the list . The picture above is the content of index.html The
    Insert picture description here
    picture above is the content of index.js.
    Running index.html will report an error. At this time, webpack is needed to solve the compatibility problem.
    Start the second step ...

> 2. Install and configure webpack in the project

  1. Run cnpm i webpack webpack-cli -Dcommand
  2. In the project root directory, create the name webpack.config.jsof the configuration file webpack
  3. In the webpack configuration file, initialize the following basic configuration
   module.exports={
   	mode:'development' // mode用来指定构建模式 开发阶段可用 development 模式
   	// development转换出来的代码不会被压缩 转换速度较快,production 模式与之相反
   	// production用于上线阶段
   }

Insert picture description here

  1. Under the scripts node of the package.json configuration file, add the dev script as follows
"scripts":{
   	"dev":"webpack" // script 节点下的脚步 可以通过 npm run执行
   }

Insert picture description here

  1. Run in a terminal npm run devcommand to start webpack project package.
    Insert picture description here
    At this time, run index.html in the browser without error.

> 3. Configure the packaged entrance and exit

Webapck 4.x version default convention: the
package entry file is src – index.jx
package output file is dist – main.js

If you want to modify the entrance and exit, webpack.config.jsadd the following configuration in

const path = require('path') // 导入node中专门操作路径的模块
module.exports = {
	entry:path.join(__dirname, './scr/index.js'), //打包入口文件路径
	output:{
		path:path.join(__dirname, './dist'), // 输出文件的存放路径
		filename:'bundle.js' //输出文件的名称
	}
}

Configuring follows:
Insert picture description here
rerun npm run devpackaged
in the directory will be more of a dist bundle.js, introduction of modified js index.html file, rerun, equally effective.
Insert picture description here

> Four. Configure the function of automatic packaging

Automatic packaging is to avoid the cumbersome steps of repacking every time you modify

  1. Run cnpm install webpack-dev-server -Dcommand to install automatic packing tool to support projects
  2. Modify the dev command in package.json-> scripts
"scripts":{
	"dev":"webpack-dev-server" 
}
  1. Modify the script script reference path in src-> index.html to "bundle.js"
    Here it can be understood that there is a hidden bundle.js in the root directory of the project
  2. Run npm run devre-packaged
  3. In the browser to access the http://localhost:8080address, view the automatic packing effect
    Insert picture description here

At this time, if you modify the code in the page and save it, it will automatically compile and you can see the effect without refreshing the page.

webpack-dev-server will start a real-time packaged http server
webpack-dev-server packaged output file (here is bundle.js), which is placed in the project root directory by default and is virtually invisible

> 5. Configure html-webpack-plugin to generate preview page

Open http://localhost:8080to see is the project directory
here if you want to see directly through the home page you need to html-webpack-pluginconfigure

  1. Run cnpm install html-webpack-plugin -Dcommand to install the plug-generated preview page
  2. Modifying webpack.config.jsthe file header area added as follows
// 导入生产预览页面的插件 得到一个构造函数
const HtmlWebpackPlugin = require('html-webpack-plugin')
const htmlPlugin = new HtmlWebpackPlugin({ // 创建插件的实例对象
	template:'./src/index/html', // 指定要用到的模版文件
	filename:'index.html' // 指定生产文件的名称 该名称存在于内存中 目录中不显示
})
  1. Modify webpack.congig.jsthe following new configuration file externally exposed configuration object
module.exports = {
	plugins = [htmlPlugin] // plugins数组是webpack打包期间会用到的一些插件列表
}

Insert picture description here

Then npm run devrefresh http://localhost:8080will be able to directly see the main page

> 6. Configure the relevant parameters of automatic packaging

When the packaging is completed, you need to manually enter the address in the browser to see the page.
If you want to automatically open the browser to enter the home page, you can refer to the following configuration

// package.json 中的配置
// --open 打包完成自动打开浏览器页面
// --host 配置IP地址
// --port 配置端口
"scripts":{
	"dev":"webpack-dev-server --open --host 127.0.0.1 --port 8888"
}

Then run npm run devit will automatically open the main page and the address and port number is the value that you configure

> Seven. Basic use of webpack's loader

By default, webpack can only package modules that end with the .js suffix. Other files that do not end with js need to call the loader to be properly packaged, otherwise they will report errors.
loaderThe loader can assist webpack to package and process specific file modules such as:

  1. Less-loader package processing. Less related files
  2. sass-loader packages and processes .scss related files
  3. url-loader packages and processes files related to the URL path in CSS

It is not necessary to configure all of them in combination with the actual project here.

【One css loader configuration】

  1. Run cnpm i style-loader css-loader -Dcommand
  2. Add the loader rule in the module-> rules array of webpack.config.js as follows:
// 所有第三方文件模块的批判规则
module:{
	rules:[
		{test:/\.css$/,use:['style-loader','css-loader']}
	]
}

【Two less loader configuration】

  1. Run cnpm i less-loader less -D
  2. Add the loader rule in the module-> rules array of webpack.config.js as follows:
// 所有第三方文件模块的批判规则
module:{
	rules:[
		{test:/\.less$/,use:['style-loader','css-loader', 'less-loader']}
	]
}

【Three scss loader configuration】

  1. Run cnpm i sass-loader node-sass -D
  2. Add the loader rule in the module-> rules array of webpack.config.js as follows:
// 所有第三方文件模块的批判规则
module:{
	rules:[
		{test:/\.scss$/,use:['style-loader','css-loader', 'sass-loader']}
	]
}

Insert picture description here
Test whether the configuration is successful.
I created a new css folder in the src directory. I
created three new files in the css file base.css, base1.less, base2.scss
and wrote the style in each style file, and then in index.js The files are imported into these three files
npm run dev. There is no error in the package operation and the styles are all effective.
Insert picture description here

> Eight. Configure postCSS to automatically add css compatible prefix

Mainly deal with browser compatibility.

  1. Run cnpm i postcss-loader autoprefixer -Dcommand
  2. Postcss created in the project root directory profiles postcss.config.jsand initial configuration
const autoprefixer = require('autoprefixer') // 导入自动添加前缀的文件
module.exports = {
	plugins:[autoprefixer] // 挂载创建
}

Insert picture description here

  1. In webpack.config.jsthe module-> rules array, add the loader rule as follows
module:{
	rules:[
		{test:/\.scss$/,use:['style-loader','css-loader', 'postcss-loader']}
	]
}

> Nine. Picture and font files in package style sheet

When there are pictures and font resources in the project, some configuration needs to be handled.
Here you can create a new images folder in the src directory and then import the pictures to test.

  1. Run cnpm i url-loader file-loader -Dcommand
  2. In webpack.config.jsthe module-> rules array, add loader rules
module:{
	rules:[
		{
			test: /\.jpg|png|gif|bmp|ttf|eot|svg|woff|woff2$/,
			use: 'url-loader?limit=70000'
		}
	]
}
// ?之后的事loader的参数项
// limit用来指定图片的大小 单位是字节byte 只有小于limit大小的图片 才会被转为base64
// base64的图片加载比较快

Insert picture description here

> Ten. (Babel) Pack and process advanced syntax in js files

  1. Install babel converter related packages cnpm i babel-loader @babel/core @babel/runtime -D
  2. Install packages related to the babel syntax plugin cnpm i @babel/preset-env @babel/plugin-transform-runtime @babel/plugin-proposal-class-properties -D
  3. Create a babel configuration file in the root directory of the project babel.config.jsand initialize the basic configuration
module.exports = {
	presets:['@babel/preset-env'],
	plugins:['@babel/plugin-transform-runtime', '@babel/plugin-proposal-class-properties']
}
  1. webpack.config.jsAdd the loader rule in the module-> rules array of as follows
// exclude 为排除项 表示babel-loader不需要处理mode-modules中的js文件
{test:/\.js$/,use:'babel-loader',exclude:/node_modules/}

During the above configuration, I wrote a method in index.js and reported an error when running.
Run it after configuration, and you can output the results.
Insert picture description here

> 11. Webpack configure VUE loader

First, create a new components folder under src, then create a new App.vue in it,
and then introduce App.vue in index.js. An error occurs.
Here, the webloader is used to configure the loader.

  1. run cnpm i vue-loader vue-template-compiler -D
  2. webpack.config.jsAdd the configuration of vue-loader in the configuration file
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
	module:{
		rules:[
		   // 其他规则
		   {test:/\.vue$/, use:'vue-loader'}
		]
	},
	plugins:[
		// 其他插件
		new VueLoaderPlugin() //确保引入这个插件
	]
}

> 12. Webpack packaging

Webpack configuration file in package.json packaging commands
the command to load the default project root directory webpack.config.jsprofile

"scripts":{
	// 用于打包的命令
	"build": "webpack -p",
}

npm run build A dist file will be generated. This file can be distributed to the server or published on the Internet, etc.

Published 41 original articles · Likes2 · Visits 1836

Guess you like

Origin blog.csdn.net/weixin_43883485/article/details/104693902