Webpack configuration for compiling module in node_modules

后端 未结 3 600
一向
一向 2020-12-30 14:23

I have problem with my webpack/babel configuration. I have installed my component-repository (es6 module without webpack configuration inside) as node_module. And in this s

3条回答
  •  一生所求
    2020-12-30 14:50

    Late post but I ran into this exact situation today. For me the problem was caused by the babel require hook:

    https://babeljs.io/docs/usage/require/

    NOTE: By default all requires to node_modules will be ignored.

    Basically, babel was not being used for any require pointing to node_modules. This is why the code worked for npm linked modules, I am guessing babel skips the ignore because the path does not contain node_modules.

    I was able to fix this by changing the ignore logic in require hook, like so:

    require('babel-register')({
      extensions: [".es6", ".es", ".jsx", ".js"],
      ignore: (absPath) => {
        if (absPath.lastIndexOf('node_modules') > absPath.indexOf('es6_module')) {
          return true;
        } else if (absPath.indexOf('es6_module') > -1) {
          return false;
        } else if (absPath.indexOf('node_modules') > -1) {
          return true;
        }
        return false;
      }
    });
    

    Of course, make sure your loader has the same logic:

    loaders: [
    
      {
        test: /\.jsx?$/,
        exclude: (absPath) => {
          if (absPath.lastIndexOf('node_modules') > absPath.indexOf('es6_module')) {
            return true;
          } else if (absPath.indexOf('es6_module') > -1) {
            return false;
          } else if (absPath.indexOf('node_modules') > -1) {
            return true;
          }
          return false;
        }
        loader: 'babel',
        query: {
                cacheDirectory: true,
                presets: ['es2015', 'react']
            }
      }
    

提交回复
热议问题