概述
本文主要介紹原始檔對映和檔案的動態監聽。
程式碼地址:github.com/fanxuewen/w…
一、原始檔對映
webpack在打包的時候,很多時候會把多個原始檔成一個bundle.js,但是當其中有一個原始檔有錯誤,我們怎麼快速的找出來呢?這就要用到sourceMap了。接著用(三)裡面的程式碼
1.修改print.js故意搞一個錯
export default function printMe() {
- alert('I get called from print.js!');
+ aler('I get called from print.js!');
}
複製程式碼
2.配置webpack.config.js中的devtool選項,devtool的選項有inline-source-map,source-map,eval-source-map等等十三個,具體請參見官方文件。我們這裡用inline-source-map
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin =require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management'
})
],
entry: {
app: './src/index.js',
print: './src/print.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
+ devtool:'inline-source-map'
};
複製程式碼
3.編譯後開啟index.html檢視,可以看到錯誤資訊告訴你在print.js的第四行有錯
二、監聽
每次我們改完原始檔,需要檢視變化的時候,都需要重新npm run build
,很不方便,因此webpack提供了三種監聽原始檔變化的的方式,這裡介紹兩種。
A.給webpack新增配置項,如下所示。但這種方式不會重新整理瀏覽器
"scripts": {
"build": "webpack",
+ "watch":"webpack --watch"
},
複製程式碼
B.使用webpack-dev-server,要使用它需如下三步
1.npm i webpack-dev-server -D
2.在webpack.config.js中配置webpack-dev-server的監聽檔案地址。webpack-dev-server預設會在localhost:8080執行一個伺服器
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin =require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: 'Output Management'
})
],
entry: {
app: './src/index.js',
print: './src/print.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
devtool:'inline-source-map',
+ devServer:{
+ contentBase: './dist'
+ }
};
複製程式碼
3.在package.json中加一條script,我們就可以執行npm start
,這時開自動開啟瀏覽器,並且可以實時修改檢視變化了。
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"watch": "webpack --watch",
+ "start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^2.0.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.30.0",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.3.1"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
複製程式碼