sourc-map:
将编译后的代码映射回原始代码,使得追踪错误和警告更加容易。
比如错误来自a.js,b.js.c.js中的b.js,source-map就会告诉你是在这个文件中。
只需配置
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
devtool: 'inline-source-map',//添加devtool
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Development'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
构建过程不会出现什么问题,然后在浏览器打开后在console口会有相关信息表示错误出自哪个文件,错误是什么
webpack有三种选择,用来在代码发生变化后自动编译代码。多数情况下,使用的是webpack-dev-server。
1. webpack-dev-server
2. webpack ‘s Watch Mode
3. webpack-dev-middleware
webpack-dev-server提供了一个web服务器,并且能够实时重新加载(live reload)。
npm i --save-dev webpack-dev-server
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
devtool: 'inline-source-map',
+ devServer: {
+ contentBase: './dist'
+ },
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Development'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
以上配置告诉webpack-dev-server,在localhost:8080下建立服务,将dist目录下的文件,作为可访问文件。
{
"name": "development",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --progress --watch",
+ "start": "webpack-dev-server --open"
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"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": "^3.0.0",
"xml-loader": "^1.2.1"
}
}
在命令行运行npm start就可以看到浏览器自动加载页面,如果修改并保存任意源文件,浏览器就会重新加载编译后的代码。
新版vue-cli自带webpack-dev-server,所以用vue-cli搭建的都不用再安装。
观察者模式会自动重新编译,缺点就是无法在浏览器自动刷新。
{
"name": "development",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
+ "watch": "webpack --watch",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"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": "^3.0.0",
"xml-loader": "^1.2.1"
}
}
npm run watch
,此时webpack编译代码,然而不会退出命令行,因为script脚本还在观察文件。
使用自动编译,有些文本编辑器有安全写入功能,会影响保存文件,需要禁用功能。
注意:source-map和自动编译仅仅适用于开发模式。在生产环境中不能使用。