How to include a few node_modules package in babel

2019-08-28 12:44发布

问题:

I'm trying to include @mycompany/package1, and @mycompany/package2 to be compiled along with the rest of my code using babel-node. Since package1 and package2 are in ES6. (Also note I'm not using Webpack)

In my jest config I added the below option into my jest config which works fine. When testing the code will compile the packages correctly

"transformIgnorePatterns": [
  "/node_modules/(?!(@mycompany)/).*/"
],

But when trying to run babel-node I get errors. In my babel.config.js

module.exports = {
  presets: [
    '@babel/preset-flow',
    [
      '@babel/preset-env',
      {
        targets: {
          node: 8
        }
      }
    ]
  ],
  plugins: ['@babel/plugin-proposal-class-properties']
};

I tried adding the below code to my babel.config.js but it still complains about ES6 errors within my node_modules/@mycompany/package1

I tried to include the viz package but then babel wouldn't compile my src files

include: [path.resolve(__dirname, 'node_modules/@mycompany/package1')]

include: ['/node_modules/((@mycompany)/).*/']

I tried to exclude everything but @mycompany packages but I still get transpile errors in my package1

exclude: [/node_modules\/(?!(@mycompany)\/).*/],

I tried playing with ignore but those don't seem like they are the right options based on reading the docs

回答1:

I found out that we can do this with webpack to help bundle the packages with the rest of your code.

This is my webpack file for NodeJS.

const path = require('path');
const nodeExternals = require('webpack-node-externals');
const webpack = require('webpack');
const spawn = require('child_process').spawn;
const nodeEnv = process.env.NODE_ENV;
const isProduction = nodeEnv === 'production';

const compiler = webpack({
  entry: ['@babel/polyfill', './src/server.js'],
  output: {
    path: path.resolve(__dirname, 'lib'),
    filename: 'server.bundle.js',
    libraryTarget: 'commonjs2'
  },
  externals: [
    nodeExternals({
      whitelist: [/@mycompany\/.*/]
    })
  ],
  plugins: plugins,
  target: 'node',
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules\/(?!(@mycompany)\/).*/,
        use: {
          loader: 'babel-loader',
          options: {
            configFile: './babel.config.js'
          }
        }
      }
    ]
  }
});

if (isProduction) {
  compiler.run((err, stats) => {
    if (err) {
      console.error(err);
      return;
    }

    console.log(
      stats.toString({
        colors: true
      })
    );
  });
} else {
  let serverControl;
  compiler.watch(
    {
      aggregateTimeout: 300,
      poll: 1000
    },
    (err, stats) => {
      if (serverControl) {
        serverControl.kill();
      }

      if (err) {
        console.error(err);
        return;
      }

      console.log(
        stats.toString({
          colors: true
        })
      );
      // change app.js to the relative path to the bundle created by webpack, if necessary
      serverControl = spawn('node', [
        path.resolve(__dirname, 'lib/server.bundle.js')
      ]);

      serverControl.stdout.on('data', data => console.log(data.toString()));
      serverControl.stderr.on('data', data => console.error(data.toString()));
    }
  );
}

Note the most important part is

  1. Adding webpack-node-externals. Since this is a node.js server we don't need to bundle the node_modules.
  2. Make sure you whitelist your package that you need to be compiled/bundled and also make sure you have your packages included to be compiled in your babel-loader
  • nodeExternal tells webpack know not to bundle ANY node_modules.
  • whitelist is saying that we should bundle the packages we listed

    externals: [ nodeExternals({ whitelist: [/@mycompany\/.*/] }) ]

  • This line means to exclude all node_modules EXCEPT @mycompany/* packages

    exclude: /node_modules\/(?!(@mycompany)\/).*/,