1.配置文件中使用插件
webpack.config.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| const CopyWebpackPlugin = require('./plugins/CopyWebpackPlugin.js') module.exports = { ... plugins: [ new CopyWebpackPlugin({ from: 'public', to: '',
ignore: '**/index.html' }), ], ... }
|
2.plugin文件
CopyWebpackPlugin.js:将静态文件打包到dist目录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| const globby = require('globby') const path = require('path') const fs = require('fs') const util = require('util') const webpack = require('webpack')
const { RawSource } = webpack.sources
const readFilePromise = util.promisify(fs.readFile)
class CopyWebpackPlugin { constructor (options) { this.options = options }
apply (compiler) {
compiler.hooks.thisCompilation.tap('CopyWebpackPlugin', (compilation) => {
compilation.hooks.additionalAssets.tapAsync('CopyWebpackPlugin', async callback => { const { from, to = '', ignore } = this.options || {}
const absoluteFromPath = path.resolve(compiler.options.context, from)
const paths = await globby(absoluteFromPath, { ignore }) console.log(absoluteFromPath)
const judgeType = (path) => { let middle = '' if (/\.js$/.test(path)) { middle = 'js' } else if (/\.css$/.test(path)) { middle = 'css' } else if (/\w(\.gif|\.jpeg|\.png|\.jpg|\.bmp)/i.test(path)) { middle = 'image' } return middle }
try { const files = await Promise.all( paths.map(async absolutePath => { const source = await readFilePromise(absolutePath) const baseName = path.basename(absolutePath) const fileName = path.join(to, judgeType(absolutePath), baseName ) const rawSource = new RawSource(source) compilation.emitAsset(fileName, rawSource) }) ) callback() } catch { callback(new Error('[CopyWebpackPlugin] loading error')) } }) }) } }
module.exports = CopyWebpackPlugin
|
3.调试技巧
- Package.json: 配置执行脚本
1 2 3 4 5
| "scripts": { ... "debug": "node --inspect-brk ./node_modules/webpack/bin/webpack.js --mode development" ... },
|
- CopyWebpackPlugin.js: 在需要断点的地方添加debugger
1 2 3 4 5
| compiler.hooks.thisCompilation.tap('CopyWebpackPlugin', (compilation) => { debugger console.log(compilation) ... })
|
- 控制台执行
- 打开网页: https://nodejs.org/en/docs/inspector

- 开始调试
