import a module from node_modules with babel but failed

后端 未结 3 1248
庸人自扰
庸人自扰 2020-12-03 14:04

I wrote a module with es6 and publish to the npm, I want to use it in another project, so I type like this:

import {ActionButton} from \'rcomponents\'


        
相关标签:
3条回答
  • 2020-12-03 14:37

    Generally, packages uploaded to npm should be precompiled, so users receive normal JS and don't require a build step. Use npm prepublish for this.

    However, if you're using webpack, you can specify an exclude function in your webpack configuration (see the webpack docs):

    module: {
      loaders: [{
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude(file) {
          if (file.startsWith(__dirname + '/node_modules/this-package-is-es6')) {
            return false;
          }
          return file.startsWith(__dirname + '/node_modules');
        },
    

    If you're using babel directly, you can write a similar ignore function in the require hook.

    0 讨论(0)
  • 2020-12-03 14:37

    You can use https://www.npmjs.com/package/babel-node-modules for this case

    npm install --save-dev babel-node-modules
    require('babel-node-modules')([
      'helloworld' // add an array of module names here 
    ]);
    

    and then it compiles listed modules as other files

    0 讨论(0)
  • 2020-12-03 14:44

    See the babel docs:

    NOTE: By default all requires to node_modules will be ignored. You can override this by passing an ignore regex.

    Generally the expectation is that modules in node_modules will already have been transpiled ahead of time, so they are not processed by Babel. If you will not be doing that, then you need to tell it what files it can process. ignore allows that.

    require("babel/register")({
        // Ignore everything in node_modules except node_modules/rcomponents.
        ignore: /node_modules\/(?!rcomponents)/
    });
    
    0 讨论(0)
提交回复
热议问题