本章继续沿用 管理输出 指南中的代码
本章中的工具仅用于开发环境,请不要在生产环境中使用
在开始前,我们先将 mode设置为’development’,并将 title 设置为 ‘Development’。
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
+ mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
plugins: [
new HtmlWebpackPlugin({
- title: 'Output Management',
+ title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
};
使用
使用source map
source maps 功能,可以将编译后的代码映射回原始源代码。如果一个错误来自于 b.js,source map 就会明确的告诉你。
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
+ devtool: 'inline-source-map',
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
};
现在,让我们来做一些调试,在 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
现在,在浏览器中打开生成的 index.html 文件,点击按钮,并且在控制台查看显示的错误。错误应该如下:
Uncaught ReferenceError: cosnole is not defined
at HTMLButtonElement.printMe (print.js:2)
选择一个开发工具
webpack 提供几种可选方式,帮助你在代码发生变化后自动编译代码:
- webpack’s Watch Mode
- webpack-dev-server
- webpack-dev-middleware
使用watch mode(观察模式)
你可以指示 webpack “watch” 依赖图中所有文件的更改。如果其中一个文件被更新,代码将被重新编译,所以你不必再去手动运行整个构建。
我们添加一个用于启动 webpack watch mode 的 npm scripts:
package.json ```javascript “scripts”: { “test”: “echo \”Error: no test specified\” && exit 1”,
- “watch”: “webpack —watch”,
“build”: “webpack”
},
现在,你可以在命令行中运行 npm run watch,然后就会看到 webpack 是如何编译代码。 然而,你会发现并没有退出命令行。这是因为此 script 当前还在 watch 你的文件。<br />src/print.js
javascript export default function printMe() {
- cosnole.log(‘I get called from print.js!’);
console.log(‘I get called from print.js!’); }
<a name="yo4BV"></a>
#### 使用webpack-dev-server
webpack-dev-server 为你提供了一个基本的 web server,并且具有 live reloading(实时重新加载) 功能。设置如下:
```javascript
npm install --save-dev webpack-dev-server
修改配置文件,告知 dev server,从什么位置查找文件:
webpack.config.js ```javascript const path = require(‘path’); const HtmlWebpackPlugin = require(‘html-webpack-plugin’);module.exports = { mode: ‘development’, entry: { index: ‘./src/index.js’, print: ‘./src/print.js’, }, devtool: ‘inline-source-map’,
- devServer: {
- static: ‘./dist’,
- },
、、、
};
以上配置告知 webpack-dev-server,将 dist 目录下的文件 serve 到 localhost:8080 下。(译注:serve,将资源作为 server 的可访问文件)<br />我们添加一个可以直接运行 dev server 的 script:<br />package.json
javascript “scripts”: { “test”: “echo \”Error: no test specified\” && exit 1”, “watch”: “webpack —watch”, - “start”: “webpack serve —open”,
“build”: “webpack”
},
```
npm start