如果您一直关注这些指南,那么您应该对一些webpack基础知识有充分的了解。 在我们继续之前,让我们考虑建立一个开发环境,让我们的生活更轻松一些。
让我们从将模式设置为’development
'开始。
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
+ mode: 'development',
entry: {
app: './src/index.js',
print: './src/print.js'
},
plugins: [
// new CleanWebpackPlugin(['dist/*']) for < v2 versions of CleanWebpackPlugin
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Development'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
使用 source maps
当webpack捆绑您的源代码时,很难找到错误和警告到其原始位置。 例如,如果将三个源文件(a.js,b.js和c.js)捆绑到一个包(bundle.js)中,并且其中一个源文件包含错误,则堆栈跟踪将简单地指向bundle。JS。 这并不总是有用,因为您可能想要确切地知道错误来自哪个源文件。
为了便于追踪错误和警告,JavaScript提供了源映射,将已编译的代码映射回原始源代码。 如果错误源自b.js,源地图将准确地告诉您。
在源地图方面有很多不同的选择。 请务必检查它们,以便根据需要进行配置。
对于本指南,让我们使用inline-source-map选项,这有助于说明目的(但不适用于生产):
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
app: './src/index.js',
print: './src/print.js'
},
+ devtool: 'inline-source-map',
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Development'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
现在让我们确保我们有一些东西要调试,所以让我们在print.js文件中创建一个错误:
src/print.js
export default function printMe() {
- console.log('I get called from print.js!');
+ cosnole.log('I get called from print.js!');
}
运行npm run build
,它应该编译成这样的东西:
...
Asset Size Chunks Chunk Names
app.bundle.js 1.44 MB 0, 1 [emitted] [big] app
print.bundle.js 6.43 kB 1 [emitted] print
index.html 248 bytes [emitted]
...
现在在浏览器中打开生成的index.html文件。 单击按钮,在控制台中查看显示错误的位置。 错误应该是这样的:
Uncaught ReferenceError: cosnole is not defined
at HTMLButtonElement.printMe (print.js:2)
我们可以看到错误还包含对发生错误的文件(print.js)和行号(2)的引用。 这很好,因为现在我们确切地知道在哪里寻找以解决问题。
选择开发工具
每次要编译代码时,手动运行npm run build很快就会变得麻烦。
There are a couple of different options available in webpack that help you automatically compile your code whenever it changes:
- webpack’s Watch Mode
- webpack-dev-server
- webpack-dev-middleware
In most cases, you probably would want to use webpack-dev-server, but let’s explore all of the above options.
使用 Watch Mode
您可以指示webpack“监视”依赖关系图中的所有文件以进行更改。 如果更新了其中一个文件,则将重新编译代码,因此您无需手动运行完整版本。
让我们添加一个npm脚本来启动webpack的Watch Mode:
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "watch": "webpack --watch",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^2.0.0",
"css-loader": "^0.28.4",
"csv-loader": "^2.1.1",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.29.0",
"style-loader": "^0.18.2",
"webpack": "^4.30.0",
"xml-loader": "^1.2.1"
}
}
现在从命令行运行npm run watch,看看webpack如何编译你的代码。 您可以看到它不会退出命令行,因为脚本当前正在查看您的文件。
现在,当webpack正在观察您的文件时,让我们删除之前介绍的错误:
src/print.js
export default function printMe() {
- cosnole.log('I get called from print.js!');
+ console.log('I get called from print.js!');
}
现在保存文件并检查终端窗口。 您应该看到webpack自动重新编译已更改的模块!
唯一的缺点是您必须刷新浏览器才能看到更改。 如果这种情况自动发生会好得多,所以让我们试试webpack-dev-server,它就是这样做的。
使用 webpack-dev-server
webpack-dev-server为您提供了一个简单的Web服务器,并能够使用实时重新加载。 我们来设置一下:
npm install --save-dev webpack-dev-server
更改配置文件以告知dev服务器在哪里查找文件:
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
app: './src/index.js',
print: './src/print.js'
},
devtool: 'inline-source-map',
+ devServer: {
+ contentBase: './dist'
+ },
plugins: [
// new CleanWebpackPlugin(['dist/*']) for < v2 versions of CleanWebpackPlugin
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Development'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
这告诉webpack-dev-server提供localhost:8080上dist目录下的文件。
让我们添加一个脚本来轻松运行开发服务器:
package.json
{
"name": "development",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
+ "start": "webpack-dev-server --open",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^2.0.0",
"css-loader": "^0.28.4",
"csv-loader": "^2.1.1",
"express": "^4.15.3",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.29.0",
"style-loader": "^0.18.2",
"webpack": "^4.30.0",
"webpack-dev-server": "^3.8.0",
"xml-loader": "^1.2.1"
}
}
现在我们可以从命令行运行npm start,我们将看到我们的浏览器自动加载我们的页面。 如果您现在更改任何源文件并保存它们,Web服务器将在编译代码后自动重新加载。 试试看!
webpack-dev-server附带了许多可配置选项。 转到文档以了解更多信息。
使用webpack-dev-middleware
webpack-dev-middleware是一个包装器,它将webpack处理的文件发送到服务器。 这在webpack-dev-server内部使用,但是它可以作为单独的包提供,以便在需要时允许更多自定义设置。 我们将看一个将webpack-dev-middleware与快速服务器相结合的示例。
让我们安装express和webpack-dev-middleware,这样我们就可以开始了:
npm install --save-dev express webpack-dev-middleware
现在我们需要对webpack配置文件进行一些调整,以确保中间件能够正常运行:
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
app: './src/index.js',
print: './src/print.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
+ publicPath: '/'
}
};
publicPath也将在我们的服务器脚本中使用,以确保在http:// localhost:3000上正确提供文件。 我们稍后会指定端口号。 下一步是设置我们的自定义快速服务器:
project
webpack-demo
|- package.json
|- webpack.config.js
+ |- server.js
|- /dist
|- /src
|- index.js
|- print.js
|- /node_modules
server.js
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const app = express();
const config = require('./webpack.config.js');
const compiler = webpack(config);
// Tell express to use the webpack-dev-middleware and use the webpack.config.js
// configuration file as a base.
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
// Serve the files on port 3000.
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
现在添加一个npm脚本,使其更容易运行服务器:
package.json
{
"name": "development",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"start": "webpack-dev-server --open",
+ "server": "node server.js",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^2.0.0",
"css-loader": "^0.28.4",
"csv-loader": "^2.1.1",
"express": "^4.15.3",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.29.0",
"style-loader": "^0.18.2",
"webpack": "^4.30.0",
"webpack-dev-middleware": "^1.12.0",
"webpack-dev-server": "^3.8.0",
"xml-loader": "^1.2.1"
}
}
现在在你的终端运行npm运行服务器,它应该给你一个类似于这样的输出:
Example app listening on port 3000!
...
Asset Size Chunks Chunk Names
app.bundle.js 1.44 MB 0, 1 [emitted] [big] app
print.bundle.js 6.57 kB 1 [emitted] print
index.html 306 bytes [emitted]
...
webpack: Compiled successfully.
现在启动浏览器并转到http:// localhost:3000。 您应该看到您的webpack应用程序正在运行并运行!