Webpack require expression external

2019-03-01 06:35发布

问题:

I have an expression require which should get resolved in runtime but I can’t get my head around the webpack config for this simple example:

import something from 'module';
import pkg from './package.json';
let a;

if (pkg.main) {
   a = require(pkg.main);
}

The resulting build should contain the module but also require ./package.json and pkg.main in runtime as commonjs modules — in other words, exclude them from the build.

My webpack.config.js so far:

var webpack = require('webpack');

module.exports = {
  entry: './src/main.js',
  output: {
    filename: '[name].js',
    path: './build'
  },
  target: 'node-webkit',
  plugins: [
    new webpack.ExternalsPlugin('commonjs', './package.json')
  ],
  module: {
    noParse: /\.min\.js/,
    exprContextRegExp: /$^/,
    exprContextCritical: false,
    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      }
    ]
  }
};

What happens now is the require for pkg.main results in webpackMissingModule exception and if I remove exprContextRegExp, the require will use context.

Thanks for any help

回答1:

For anyone wondering: you can solve it with this plugin:

function() {
  this.parser.plugin('call require', function(expr) {
    if (expr.arguments.length !== 1) {
      return;
    }

    const param = this.evaluateExpression(expr.arguments[0]);
    if (!param.isString() && !param.isConditional()) {
      return true;
    }
  });
}

Anything that cannot be resolved by webpack will be left as is.