说明

​玩转webpack​​课程学习笔记。

推荐阅读​​阮一峰的网络日志-JavaScript Source Map 详解​

什么是 source map

​Source map​​就是一个信息文件,里面储存着位置信息。也就是说,转换后的代码的每一个位置,所对应的转换前的位置。

使⽤ source map

1、作⽤:通过 source map 定位到源代码

2、开发环境开启,线上环境关闭

  • 线上排查问题的时候可以将​​sourcemap​​ 上传到错误监控系统

source map 关键字

  • ​source map​​​: 产⽣​​.map​​ ⽂件
  • ​eval​​​: 使⽤​​eval​​ 包裹模块代码
  • ​cheap​​: 不包含列信息
  • ​inline​​​: 将​​.map​​​ 作为​​DataURI​​​ 嵌⼊,不单独⽣成​​.map​​ ⽂件
  • ​module​​​: 包含​​loader​​​ 的​​sourcemap​

source map 类型

webpack进阶篇(十九):使⽤ source map_webpack

例子

1、在​​search​​​文件夹里的​​index.js​​​添加​​debugger​

import React from 'react';
import ReactDOM from 'react-dom';
import './search.less';
import logo from './images/logo.png';
console.log(logo);

class Search extends React.Component {
render() {
debugger;
return <div className="search-text">
凯小默的博客666
<img src={ logo } />
</div>
}
}

ReactDOM.render(
<Search/>,
document.getElementById('root')
)

2、配置开发配置

const glob = require('glob');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

const setMPA = () => {
const entry = {};
const htmlWebpackPlugins = [];
const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'));

Object.keys(entryFiles)
.map((index) => {
const entryFile = entryFiles[index];

const match = entryFile.match(/src\/(.*)\/index\.js/);
const pageName = match && match[1];

entry[pageName] = entryFile;
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
inlineSource: '.css$',
template: path.join(__dirname, `src/${pageName}/index.html`),
filename: `${pageName}.html`,
chunks: ['vendors', pageName],
inject: true,
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
})
);
});

return {
entry,
htmlWebpackPlugins
}
}

const { entry, htmlWebpackPlugins } = setMPA();

module.exports = {
entry: entry,
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
mode: 'development',
module: {
rules: [
{
test: /.js$/,
use: 'babel-loader'
},
{
test: /.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /.less$/,
use: [
'style-loader',
'css-loader',
'less-loader'
]
},
{
test: /.(png|jpg|gif|jpeg)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10240
}
}
]
},
{
test: /.(woff|woff2|eot|ttf|otf)$/,
use: 'file-loader'
},
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin()
].concat(htmlWebpackPlugins),
devServer: {
contentBase: './dist',
hot: true
}
};

3、先不加​​source-map​​​,启动服务​​npm run dev​

webpack进阶篇(十九):使⽤ source map_webpack_02

4、添加​​source-map​​配置

: {
contentBase: './dist',
hot: true
},
devtool: 'source-map'
};

webpack进阶篇(十九):使⽤ source map_css_03