How to configure and build the environment for Webpack + ES6
This time I will show you how to configure and build the environment for Webpack ES6. What are the precautions for configuring and building the environment for Webpack ES6? The following is a practical case, let's take a look.
1. Download node.js and npm2. Replace the image source with the Taobao image2, create the directory and install webpackCreate the project
in the command line Enter npm init -yInstall webpack
Install webpack globally and enter ## on the command line #npm install webpack -g npm install webpack-cli -g
In webpack4 webpack and webpack-cli are separated, so they need to be installed separately
Install a webpack in the current directory
Enter on the command line
npm installwebpack-cli--save-dev npm installwebpack--save-dev
The parameter -g means installation into the global environment. The package is installed in the node_modules folder under the Node installation directory, usually in the \Users\username\AppData\Roaming\ directory. , you can use npm root -g to view the global installation directory.
After global installation, it can be used by the command line (command line). Users can directly run the components supported by this component package in the command line. Command, as shown below, the cmd file after global installation of cnpm
The local installation method is to enter the command: npm install eslint or npm install eslint --save -dev, etc. The parameter --save-dev means writing your installation package information into the devDependencies field of the package.json file. The package is installed in the node_modules folder in the root directory where we execute the command. After local installation, you can directly introduce the modules in the node_modules directory of the project through require(). As shown in the following example, after local installation, directly require('webpack') in gulpfile.js. As shown below
When we use it, it is recommended to use local installation. Local installation allows each project to have an independent package, which is not affected by the global package and is convenient for the project. Move, copy, package, etc. to ensure interdependence between different versions of packages. The disadvantages are that it takes a long time to install and takes up a lot of memory. However, as disks become larger and larger today, its disadvantages can be ignored.
1. We create a folder src in the directory to store the source files
2. Create a folder build to store the compilation The following file3. Create a new index.html file
4. Create the configuration file webpack.config.js
Create index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hi webpack4!</title> </head> <body> <script src = "../build/bundle.js"></script> </body> </html>
Create Main.js
document.write("Hi webpack4 + ES6!");
Configure webpack.config.js
var path = require('path'); var appPath = path.resolve(dirname, './src/Main.js'); var buildPath = path.resolve(dirname, './build'); module.exports = { entry: appPath,//整个页面的入口文件 output: { path: buildPath,//打包输出的地址 filename: "bundle.js",//输出的文件名称 }, module: { } }
Enter on the command line
webpack --mode developmentbundle.js
webpack --mode development
//Main.js import {Dog} from "./Dog"; class Main { constructor() { document.write("Hi webpack4 + ES6!"); console.info("Hi webpack4 + ES6"); let dog = new Dog(); } } new Main();
打开index.html
webpack-v4.10.2会识别es6语法并编译
我们也可以使用babel来对ES6进行编译
输入 npm install babel-loader --save-dev
修改配置项webpack.config.js
var path = require('path'); var appPath = path.resolve(dirname, './src/Main.js'); var buildPath = path.resolve(dirname, './build'); module.exports = { entry: appPath,//整个页面的入口文件 output: { path: buildPath,//打包输出的地址 filename: "bundle.js",//输出的文件名称 }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader?presets=es2015' } ] } }
两者的编译结果存在部分差异,并不影响正确性。
三,webpack加载资源文件根据模版文件生成访问入口
我们在部署项目时,部署的是build中的文件,并不会将我们src/index.html作为访问的入口,因此,我们需要将index.html移动到build下,但是简单的复制过去是不行的,由于文件目录的不同,如果使用了相对路径,那么就会找不到文件。这时候我们就可以用到webpack的插件 html-webpack-plugin,它可以将我们src/index.html作为模版,生成一份新的index.html在build下。
具体的用法请查看https://github.com/jantimon/html-webpack-plugin#third-party-addons
在本例只是简单使用。
执行
npm i --save-dev html-webpack-plugin
之前我们是将index.html中的js入口指定为build/bundle.js,使用这个插件后,我们设置它直接指向Main.js
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hi webpack4!</title> </head> <body> <script src = "Main.js"></script> </body> </html>
/* webpack.config.js */ var path = require('path'); var appPath = path.resolve(dirname, './src/Main.js'); var buildPath = path.resolve(dirname, './build'); const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: appPath,//整个页面的入口文件 output: { path: buildPath,//打包输出的地址 filename: "bundle.js",//输出的文件名称 }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader?presets=es2015' } ] }, plugins: [ new HtmlWebpackPlugin({ /* template 参数指定入口 html 文件路径,插件会把这个文件交给 webpack 去编译, webpack 按照正常流程,找到 loaders 中 test 条件匹配的 loader 来编译,那么这里 html-loader 就是匹配的 loader html-loader 编译后产生的字符串,会由 html-webpack-plugin 储存为 html 文件到输出目录,默认文件名为 index.html 可以通过 filename 参数指定输出的文件名 html-webpack-plugin 也可以不指定 template 参数,它会使用默认的 html 模板。 */ template: './src/index.html', /* 因为和 webpack 4 的兼容性问题,chunksSortMode 参数需要设置为 none https://github.com/jantimon/html-webpack-plugin/issues/870 */ chunksSortMode: 'none' }), ] }
输入指令打包我们会发现,build下的index.html已经生成,并且指向了编译的后js
使用webpack打包图片和文件
我们新增资源文件夹asset 并添加一张图片
import {Dog} from "./Dog"; class Main { constructor() { document.write("Hi webpack4 + ES6!"); console.info("Hi webpack4 + ES6"); let dog = new Dog(); document.write(""); } } new Main();
并将图片展示到页面
图裂了,找不到资源,大家应该都猜到了,应为在编译时,直接将 添加到了build/index.html,build下并没有asset包,所以找不到资源。难道我们需要在build下在建立一个资源文件夹吗?答案是不用,webpack可以对图片的路径进行转换和图片打包。
输入指令
npm install url-loader --save-dev npm install file-loader --save-dev
/*webpack.config.js*/ var path = require('path'); var appPath = path.resolve(dirname, './src/Main.js'); var buildPath = path.resolve(dirname, './build'); const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { entry: appPath,//整个页面的入口文件 output: { path: buildPath,//打包输出的地址 filename: "bundle.js",//输出的文件名称 }, module: { rules: [ { test: /\.js$/, loader: 'babel-loader?presets=es2015' } , { //url-loader的主要功能是:将源文件转换成DataUrl(声明文件mimetype的base64编码) //小于limit字节,以 base64 的方式引用,大于limit就交给file-loader处理了 //file-loader的主要功能是:把源文件迁移到指定的目录(可以简单理解为从源文件目录迁移到build目录 test: /\.(jpg|png|gif)$/, loader: 'url-loader?limit=8192&name=asset/[hash:8].[name].[ext]' } ] }, plugins: [ new HtmlWebpackPlugin({ /* template 参数指定入口 html 文件路径,插件会把这个文件交给 webpack 去编译, webpack 按照正常流程,找到 loaders 中 test 条件匹配的 loader 来编译,那么这里 html-loader 就是匹配的 loader html-loader 编译后产生的字符串,会由 html-webpack-plugin 储存为 html 文件到输出目录,默认文件名为 index.html 可以通过 filename 参数指定输出的文件名 html-webpack-plugin 也可以不指定 template 参数,它会使用默认的 html 模板。 */ template: './src/index.html', /* 因为和 webpack 4 的兼容性问题,chunksSortMode 参数需要设置为 none https://github.com/jantimon/html-webpack-plugin/issues/870 */ chunksSortMode: 'none' }), ] }
编译后的目录如下(新增一张较大的图片book用于展示file-loader)
页面效果如下,图是随便找的,见谅。
注意:当我们引入一些资源需要使用变量引用时,像这样引用的话是会编译失败的
图片并没有像上图一样打包到asset中
当我们在require一个模块的时候,如果在require中包含变量,像这样:
require("./asset/" + name + ".png");
那么在编译的时候我们是不能知道具体的模块的。但这个时候,webpack也会为我们做些分析工作:
1.分析目录:'./asset';
2.提取正则表达式:'/^.*\.png$/';
于是这个时候为了更好地配合wenpack进行编译,我们应该给它指明路径
使用webpack打包css文件
就像图片一样,webpack也提供了样式文件的打包,
npm install style-loader --save-dev npm install css-loader --save-dev
//rules中添加 { //css-loader使能够使用类似@import和url(...)的方法实现require,style-loader将所有的计算后的样式加入页面中 //webpack肯定是先将所有css模块依赖解析完得到计算结果再创建style标签。因此应该把style-loader放在css-loader的前面 test: /\.css$/, use: ['style-loader', 'css-loader'] }
添加main.css文件,
span{color:red;}
目录如下
四,搭建webpack微服务器
在开发过程中,我们不可能修改一次,打包一次。因此我们需要使用到webpack提供的服务器。
cnpm install webpack-dev-server --save-dev
为了方便我们在pack.json中配置脚本。
"start":"webpack-dev-server--modedevelopment", "dev":"webpack--modedevelopment", "build":"webpack--modeproduction"
npm run start
启动成功后访问服务地址,就可以实现修改代码之后,页面实时刷新。
启动时使用的是默认配置。
当我们需要个性化设置时,在webpack.config.js中添加设置即可
//以下是服务环境配置 devServer:{ port:8085,//端口 host:'localhost',//地址 inline:true,//用来支持dev-server自动刷新 open:true,//开启webpack-dev-server时自动打开页面 historyApiFallback:true, contentBase:path.resolve(dirname),//用来指定index.html所在目录 publicPath:'/build/',//用来指定编译后的bundle.js的目录 openPage:"build/index.html"//指定打开的页面 }
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of How to configure and build the environment for Webpack + ES6. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Windows Recovery Environment (WinRE) is an environment used to repair Windows operating system errors. After entering WinRE, you can perform system restore, factory reset, uninstall updates, etc. If you are unable to boot into WinRE, this article will guide you through fixes to resolve the issue. Unable to boot into the Windows Recovery Environment If you cannot boot into the Windows Recovery Environment, use the fixes provided below: Check the status of the Windows Recovery Environment Use other methods to enter the Windows Recovery Environment Did you accidentally delete the Windows Recovery Partition? Perform an in-place upgrade or clean installation of Windows below, we have explained all these fixes in detail. 1] Check Wi

In this article, we will learn about the differences between Python and Anaconda. What is Python? Python is an open source language that places great emphasis on making the code easy to read and understand by indenting lines and providing whitespace. Python's flexibility and ease of use make it ideal for a variety of applications, including but not limited to scientific computing, artificial intelligence, and data science, as well as creating and developing online applications. When Python is tested, it is immediately translated into machine language because it is an interpreted language. Some languages, such as C++, require compilation to be understood. Proficiency in Python is an important advantage because it is very easy to understand, develop, execute and read. This makes Python

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

PHP integrated environment packages include: 1. PhpStorm, a powerful PHP integrated environment; 2. Eclipse, an open source integrated development environment; 3. Visual Studio Code, a lightweight open source code editor; 4. Sublime Text, a A popular text editor, widely used in various programming languages; 5. NetBeans, an integrated development environment developed by the Apache Software Foundation; 6. Zend Studio, an integrated development environment designed for PHP developers.
