purpose
This is a reference for those who want to write a Webpack loader, and I can come back to it occasionally as I tend to forget.
Look at the usage
Write a loader that simply replaces the URL
module.exports = {
module: {
rules: [{
test: /\.js$/,
loader: 'path-replace-loader'.exclude: /(node_modules)/,
options: {
path: 'ORIGINAL_PATH'.replacePath: "REPLACE_PATH"}}}}]Copy the code
Just as above
The source code to the
const fs = require("fs")
const loaderUtils = reuqire('loader-utils')
module.exports = function(source) {
// Who does this refer to? Point to a load runner object.
// Conversion requires a lot of calculation and is very time-consuming, so the following line of code does not call the corresponding Loader to perform conversion operation when the file to be processed or its dependent file does not change
this.cacheable && this.cacheable()
// Handle asynchronous methods within webpack
const callback = this.async()
/ / configuration
const options = loaderUtils.getOptions(this)
if(this.resourcePath.indexOf(options.path) > -1) {
const newPath = this.resourcePath.replace(options.path, options.replacePath)
fs.readFile(newPath, (err, data) = > {
if(err) {
if(err.code === 'ENOENT') return callback(null, source)
}
// Use this method to add the new file to the WebPack dependency and return the content via callback
this.addDependency(newPath)
callback(null, data)
})
}else {
callback(null, source)
}
}
// Tells Webpack whether the Loader needs binary data via the exports.raw property
module.exports.raw = true
Copy the code
conclusion
About a simple loader out, in fact, if you want to copy, and then copy, or can be used, so this first, welcome to tell me in the comments who this refers to