Webpack require expression external

2019-03-01 06:40发布

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条回答
做个烂人
2楼-- · 2019-03-01 06:59

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.

查看更多
登录 后发表回答