A Webpack loader that transforms modules (tasks) into results at build time.
You can see this loader as val-loader with APIs re-designed. We believe task-loader is much more useful when there're shared tasks in both frontend and backend. Also, if you want to load assets but cannot find a proper loader, this loader allows you to quickly prototype a custom loader.
- Node v8.0.0 or above
- Webpack v4.0.0 or above
Add a new rule in webpack.config.js.
// webpack.config.js
module.exports = {
module: {
rules: [{
test: /\.task.js$/,
loader: 'task-loader',
exclude: /node_modules/
}]
}
}
Note that the rule
/\.task.js$/
is a subset of/\.js$/
. Be careful if you use babel or similar loaders to transform your source code.
Then, modules with name matching /\.task.js$/
will be loaded and transformed via task-loader.
// getMs.task.js
module.exports = ({ years }) => years * 365 * 24 * 60 * 60 * 1000
// app.js
import Ms from './getMs.task?years=2' // Ms will be 63072000000
// ...
Yon can also export an array or a plain object from the task module. task-loader will respect the shape of the exported value and only transform functions into results in-place.
The exported task functions will be executed under the context of loader
proxies. The this
variable has the following properties/functions
only set to true
when loaded by task-loader. Use this property to split
frontend/backend logic.
only set to true
when loaded by Webpack. See loader.webpack.
This function directly call loader.cacheable.
Like loader.addDependency but these functions can work with relative paths.
This function directly call loader.clearDependencies.
This function allows you to run other tasks. Note that the target tasks will be automatically added to dependencies.
-
task
: path of the target task, can be relative. -
query
: a plain object ornull
served as parameters. -
callback(err, value)
: callback function that will be called when the task is succefully executed.
The async version of the run
method.
This functions directly call loader.emitFile.
- When or how much times task modules are loaded/executed depend on Webpack's caching mechanism. Make sure the side effects will not cause race conditions.
- The query values and output results of the task modules should be able to be JSON-stringified.
- Cache compiled functions
MIT