Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

javascript - Webpack require expression external

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...