Does anyone know how to insert and reuse a function in a Webpack plugin? Like from my plugin insert that function myFunction()
and call it from the generated bundle?
Background information:
I'm replacing some paths to some assets that are inside other libraries.
- Library A uses file1.afm to file14.afm
- Library B uses file1.trie to file4.trie
I put these files in my package using file-loader
and then I require each file:
const f1 = require('file1.afm')
And so forth for every single file.
But Library A and B are doing something like the following:
data = base64.toByteArray(fs.readFileSync('../src/js/somePath/inLibrary/Private/file1.afm', 'base64'));
For every single file. I want to replace that path with the correct path to the bundle, but the __dirname
doesn't help. That's why I want to use callsites.
What I want to do is insert callsites as a global dependency on my bundle and use it similarly to __webpack_require__(moduleId)
so that I can pull in the executing js file path (__dirname
or __filename
don't work)
So in theory I would insert callsites()[0].getFileName() + __webpack_require__(moduleId)
So far my config looks like this, and webpack-file-resolver
is the current plugin i'm doing:
const path = require('path')
const webpackTs = require('webpack-config-typescript')
var WebpackFileResolver = require('webpack-file-resolver')
let config = {
entry: path.join(__dirname, 'src/handler.ts'),
target: 'node',
output: {
filename: 'deploy/handler_[hash].js',
libraryTarget: 'commonjs',
path: path.join(__dirname)
}
}
config = webpackTs.ts(config)
config.module.rules.push({
test: /\.(ttf|trie|afm)$/,
loader: "file-loader",
options: {
name: "[name].[ext]",
outputPath: "deploy",
publicPath: "./"
},
})
config.plugins.push(new WebpackFileResolver({
test: /\.(trie|afm)$/,
serverPath: "./"
}))
module.exports = config
So far this is what I got:
const ConcatSource = require("webpack-sources").ConcatSource
function getRequires (options, chunks) {
return chunks.reduce((c, chunk) => {
chunk.forEachModule((module) => {
const deps = module && module.fileDependencies && module.fileDependencies || []
deps.forEach((filepath) => {
if(options.test.test(filepath)) {
c.add({
path: filepath,
id: module.id
})
}
})
})
return c
}, new Set())
}
class WebpackFileResolverPlugin {
constructor(options = {}) {
this.options = options
}
apply(compiler) {
const options = this.options
compiler.plugin('compilation', (compilation) => {
compilation.plugin('optimize-chunk-assets', (chunks, done) => {
const requires = getRequires(options, chunks)
replaceBundleReadDir(compilation, chunks, requires)
done()
})
})
}
}
function replaceBundleReadDir(compilation, chunks, requires){
chunks.forEach(function (chunk) {
chunk.files.forEach(function (fileName) {
replaceSource(compilation, fileName, requires)
})
})
}
function replaceSource(compilation, fileName, requires){
let result = compilation.assets[fileName].source()
const source = []
requires.forEach((require) => {
let buffer = []
for (let c of result) {
if (c !== '\n') {
buffer.push(c)
} else {
const line = buffer.join('')
const newLine = replaceFsReadDir (require, line)
if (newLine !== undefined) {
result = result.replace(line, newLine)
}
buffer = []
}
}
})
compilation.assets[fileName] = new ConcatSource(result)
}
function replaceFsReadDir (require, line) {
const webpackRequire = '__webpack_require__'
const fileName = require.path.replace(/^.*[\\\/]/, '')
const fileStartMarker = line.indexOf(fileName)
const readDirMarker = line.lastIndexOf('readFile')
if (fileStartMarker !== -1 && readDirMarker !== -1) {
let fileEndMarker = line.indexOf(')', fileStartMarker)
let getEnd = line.slice(fileStartMarker, fileEndMarker + 1)
fileEndMarker = (getEnd.length > fileName.length + 2) ? line.indexOf(',', fileStartMarker) : fileEndMarker
const startSlice = line.indexOf('(', readDirMarker) + 1
const newLine = `${line.slice(0, startSlice)}${webpackRequire}(${require.id})${line.slice(fileEndMarker)}`
return newLine
} else {
return undefined
}
}
module.exports = WebpackFileResolverPlugin