hsiaosiyuan0/mole

conditional package require

Closed this issue · 1 comments

the mole's dependency scanner should support the functionality called "conditional package require"(you wouldn't search it, i name it personally)

consider below code which copied from the entry file of the famous React package:

'use strict';

if (process.env.NODE_ENV === 'production') {
  module.exports = require('./cjs/react.production.min.js');
} else {
  module.exports = require('./cjs/react.development.js');
}

bundle tools like webpack can understand the conditional require semantic in above code process.env.NODE_ENV === 'production', so there is only one of either react.production.min.js or react.development.js appears in the final dependency-graph. such ability should come with mole's dependency scanner as well

as a footnote, despite the example above uses the commonjs's package including manner require, it does not mean that condition import interpretation is meaningless in the esm situation by considering the dynamic import

the implementation of this functionality needs to be divided into 2 parts, one for commonjs, one for esm

for the commonjs part, these steps should be taken into account:

  • 1. distinguish the require calls, note the callee require should refer to the global require function, rather than bound to other values
  • 2. find the conditions which may cause the require happen, the places where the conditions could appear are the IfStatement and ConditionalExpression
  • 3. evaluate the conditions then select their corresponding requires

for the esm part, all the steps are same with the steps in commonjs except the first step:

  1. find the import calls, no need to ensure if the callee import refers to the global import function, since the import was never a function, it's a keyword instead see import - syntax