javascript - Webpack: How can I create a loader for "webpack" which takes an array of dependencies? -
for example, use amd definition in project, , use "webpack" project building. it's possible create loader take dependencies in array format?
define( [ 'mysuperloader![./path/dependency-1, ./path/dependency-2, ...]' ], function() { // ... logic here } ) project example: github
if want port load-plugin's behavior webpack, need this:
1. create custom resolver
this because mysuperloader![./path/dependency-1, ./path/dependency-2, ...] not point single file. when webpack tries load file, first:
- resolves file path
- loads file content
- matches , resolves loaders
- passes file content loader chain
since [./path/dependency-1, ./path/dependency-2, ...] not proper file path, there work do. not proper json.
so, our first goal turn mysuperloader!some/random/file?["./path/dependency-1", "./path/dependency-2", ...]. done creating custom resolver:
// webpack.config.js var customresolverplugin = { apply: function (resolver) { resolver.plugin("resolve", function (context, request) { const matchloadrequest = /^\[(.+)]$/.exec(request.path); if (matchloadrequest) { request.query = '?' + json.stringify( matchloadrequest[1] .split(", ") ); request.path = __filename; } }); } }; module.exports = { ... plugins: [ { apply: function (compiler) { compiler.resolvers.normal.apply(customresolverplugin); } } ] }; notice request.path = __filename;? need give webpack existing file not throw error. generate content anyway. not elegant solution, works.
2. create our own load-loader (yeah!)
// loadloader.js const path = require("path"); function loadloader() { return json.parse(this.request.match(/\?(.+?)$/)[1]) .map(module => `exports['${path.basename(module, '.js')}'] = require('${module}');` ) .join('\n'); } module.exports = loadloader; this loader parses request's query have re-written our custom resolver , creates commonjs module looks this
exports['dependency-1'] = require('path/to/dependency-1'); exports['dependency-2'] = require('path/to/dependency-2'); 3. alias our own load-loader
// webpack.config.js ... resolveloader: { alias: { load: require.resolve('./loadloader.js') } }, 4. configure root
since /path/to/dependency-1 root-relative, need add root webpack config
// webpack.config.js resolve: { root: '/absolute/path/to/root' // __dirname }, this neither beautiful nor ideal solution, should work makeshift until you've ported modules.
Comments
Post a Comment