加载本地 Loader

1、path.resolve
可以简单通过在 rule 对象设置 path.resolve 指向这个本地文件

{
  test: /\.js$/
  use: [
    {
      loader: path.resolve('path/to/loader.js'),
      options: {/* ... */}
    }
  ]
}

  

2、ResolveLoader
这个就是上面我用到的方法。ResolveLoader 用于配置 Webpack 如何寻找 Loader。 默认情况下只会去 node_modules 目录下寻找,为了让 Webpack 加载放在本地项目中的 Loader 需要修改 resolveLoader.modules
假如本地的 Loader 在项目目录中的 ./loaders/loader-name 中,则需要如下配置:

module.exports = {
  resolveLoader:{
    // 去哪些目录下寻找 Loader,有先后顺序之分
    modules: ['node_modules','./loaders/'],
  }
}

  

加上以上配置后, Webpack 会先去 node_modules 项目下寻找 Loader,如果找不到,会再去 ./loaders/ 目录下寻找。
3、npm link
npm link 专门用于开发和调试本地 npm 模块,能做到在不发布模块的情况下,把本地的一个正在开发的模块的源码链接到项目的 node_modules 目录下,让项目可以直接使用本地的 npm 模块。 由于是通过软链接的方式实现的,编辑了本地的 Npm 模块代码,在项目中也能使用到编辑后的代码。

完成 npm link 的步骤如下:

  • 确保正在开发的本地 npm 模块(也就是正在开发的 Loader)的 package.json 已经正确配置好;
  • 在本地 npm 模块根目录下执行 npm link,把本地模块注册到全局;
  • 在项目根目录下执行 npm link loader-name,把第2步注册到全局的本地 Npm 模块链接到项目的 node_moduels 下,其中的 loader-name 是指在第1步中的package.json 文件中配置的模块名称。

链接好 Loader 到项目后你就可以像使用一个真正的 Npm 模块一样使用本地的 Loader 了。

1.封装自定义的功能loader

(格式很简单,重点在于loader-utils,loaderUitls.getOptions可获取webpack配置rules中的options以供使用 )

这只是一个简单的替换路径loader,具体别的需求的loader就可以自己编写内容了

 

 

 2. 自定义插件

compiler和compilation
// MyPlugin.js
function MyPlugin(options) {
  this.options = options;
}
MyPlugin.prototype.apply = function(compiler) {
  // ...
  compiler.plugin('compilation', function(compilation) {
    console.log('The compiler is starting a new compilation...');
    compilation.plugin('html-webpack-plugin-before-html-processing', function(htmlPluginData, callback) {
      htmlPluginData.html += 'The magic footer';
      callback(null, htmlPluginData);
    });
  });
};
module.exports = MyPlugin;

事件: 通过执行下列事件来允许其他插件更改html: 异步事件: html-webpack-plugin-before-html-generation html-webpack-plugin-before-html-processing html-webpack-plugin-alter-asset-tags html-webpack-plugin-after-html-processing html-webpack-plugin-after-emit 同步事件: html-webpack-plugin-alter-chunks

配合htmlWebpackPlugin插件,给html中link标签加id

my-plugin.js

function MyPlugin(options) {
  this.options = options;
}
MyPlugin.prototype.apply = function(compiler) {
  compiler.plugin('compilation', function(compilation) {
    compilation.plugin('html-webpack-plugin-alter-asset-tags', function(htmlPluginData, callback) {
      if (htmlPluginData.head && htmlPluginData.head.length) {
        htmlPluginData.head.forEach(item => {
          if (item.attributes) {
             let href = item.attributes.href;
             item.attributes.id = href.substring(href.indexOf('css/') + 4, href.indexOf('.'));
          }
        });
      }
      callback(null, htmlPluginData);
    });
  });
};
module.exports = MyPlugin;

然后 webpack.config.js 中配置为:

let MyPlugin = require('./my-plugin.js')
// ...
plugins: [
  new MyPlugin({options: ''})
]
posted on 2019-12-25 01:45  ygunoil  阅读(1278)  评论(0编辑  收藏  举报