Usage
npm install --save-dev babel-plugin-on-demand-loading
使用方式一:在 .babelrc
里进行配置(推荐):
// .babelrc "plugins": "on-demand-loading" "library": "diana" // 配合 webpack 里的 babel-loadermodule: rules: test: /\.js$/ loader: "babel-loader"
使用方式二:在 webpack 里进行配置:
module: { rules: [{ test: /\.js$/, loader: "babel-loader",+ options: {+ plugins: [+ ["on-demand-loading", { "library": "diana" }],+ ]+ } }]},
Principle
上述代码经过此插件转换后等同于下列代码,从而实现按需加载
源码分析
const babel = ;const types = ; module { return visitor: { let node = pathnode let specifiers = node if refoptslibrary === nodesourcevalue && !types // 过滤 import { equal } from 'diana' && !types // 过滤 import * as _ from 'diana' let newImports = specifiers path } }