Babel plug-in

Write a plug-in for Babel that modules load on demand

When we import the utility functions specified in LoDash, we package the entire LoDash

import {flattenDeep, chunk} from 'lodash'

Copy the code

I’m going to write it on demand but it’s a little bit cumbersome and we want to automatically decompose it from the top to the bottom so we’re going to write a Babel plug-in

import flattenDeep from 'lodash/flattenDeep'
import chunk from 'lodash/chunk'
Copy the code

Install package

npm i babel-core -D
npm i babel-types -D
Copy the code

Plug-in to write

Create index.js in the babel-plugin-extract directory under node_modules of the current project


const babel = require('babel-core');
const types = require('babel-types'); // import {deep, chunk} from the flattener'lodash'A flattener is written like this: // import deep from'lodash/flattenDepp'
// import chunk from 'lodash/chunk'// Babel transforms the source code into an AST, iterates through the AST tree (which is a JS object), makes some changes to the tree, and then converts the AST into code, which is the source code.letVisitor = {// Trigger this function when import statements are parsed ImportDeclaration(path, ref = {opTS: {}}) {// Path statement abstracts syntax tree OPTS plug-in parameterslet node = path.node;
        let{specifiers} = node; // Check whether the import library is specified by the.babelrc library attribute and load the import on demand if it is not the default importif(ref.opts.library === node.source.value && ! types.isImportDefaultSpecifier(specifiers[0])) {letNewImports = specifiers. Map (specifier => (// walks through the description descriptors for each imported package Types. ImportDeclaration ([types. ImportDefaultSpecifier (specifiers. Local)], / / generated import statements, such as the import the chunk from'lodash/chunk'
                types.stringLiteral(`${node.source.value}/${specifier.local.name}`)))); // Replace path.replaceWithmultiple (newImports) with new; } } } module.exports =function(Babel) {// Export plug-inreturn{visitor} // Property name fixed to visitor (visitor)};Copy the code

Configuration. Babelrc

{
    "presets": [
        "env"."stage-0"]."plugins": [["extract"// Configure plugins {"library": "lodash"// specify the library to handle}]]}Copy the code

build

NPM run build // Now the compiled bundle.js is smallerCopy the code

The source address

NPM run build babel-plugin-extract NPM run build babel-plugin-extract NPM run build babel-plugin-extract

reference

  • Analyze the Babel
  • Babel plug-in development guide
  • Babel started from scratch
  • Babel plugin
  • AST Abstract syntax tree online conversion
  • babel-types