Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Babel does not transpile imported modules from 'node_modules'

I got a problem with transpiling imported modules from node_modules. Babel for some reason doesn't transpile imported module from node_modules, but transpile modules imported from src.

Here is an example repo: https://github.com/NikitaKA/babeltest

main.js

// result code contains const and let, but it shouldn't. :(

index.js

import qs from 'query-string; // not transpiled
import lib from './lib' // transpiled

const query = qs.parse(window.location.search);

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

.babelrc

{
  "presets": [
    ["@babel/preset-env", {
      "modules": false,
      "targets": {
        "chrome": 39
      }
    }],
    ["@babel/preset-stage-1", {
      "modules": false,
      "decoratorsLegacy": true,
      "pipelineProposal": "minimal"
    }]
  ],
  "plugins": [
    "transform-es2015-constants",
    "@babel/plugin-transform-block-scoping",
    "@babel/plugin-transform-runtime"
  ]
}
like image 251
NikitaK Avatar asked Jul 11 '18 15:07

NikitaK


3 Answers

The solution in this case is to transpile the module again, this can be done by modifying the exclude property in your webpack config:

{
  test: /\.js$/,
  exclude: /node_modules\/(?!(es6-module|another-es6-module)\/).*/,
},

Modules es6-module and another-es6-module will no longer be ignored by webpack and will be transpiled with the rest of your source code.

See the GitHub issue on the webpack project.

Tested with [email protected], [email protected] and [email protected]

like image 183
Rafal Enden Avatar answered Nov 10 '22 17:11

Rafal Enden


To expand upon my comments:

You really don't want to transpile all of node_modules – it'll take a long time, and most of the code there should already be ES5 (unless they're actually ES6 modules, in which case the ES6 entry point is announced as "module" in the package.json manifest).

[email protected] isn't, and it says so in its README:

This module targets Node.js 6 or later and the latest version of Chrome, Firefox, and Safari. If you want support for older browsers, use version 5: npm install query-string@5.

like image 29
AKX Avatar answered Nov 10 '22 18:11

AKX


If you're using Vue, there is a simple solution. Just list your module in transpileDependencies:

vue.config.js

module.exports = {
   publicPath: '',
   outputDir: 'www',
   transpileDependencies: [
    'query-string'
  ],
}
like image 1
NikitaK Avatar answered Nov 10 '22 18:11

NikitaK