Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External imports in Babel 7 do not get transpiled

I'm currently migrating a codebase from Babel 6 to 7. The code is made up of multiple individual projects with their own configs.

The main project imports files from external however the scripts being imported from external by main aren't being transpiled and fails on "Unexpected token import". Scripts located directly in main do transpile correctly.

I'm using the following command within the main project to transpile the scripts:

babel-node ./index.js

Another project uses Webpack to do the same thing and handles everything correctly.

This setup also worked fine with Babel 6.


.babelrc for main

{
"ignore": [
    "node_modules"
],
"presets": [
    ["@babel/preset-env", {
        "targets": {
            "node": "current"
        },
        "useBuiltIns": "entry"
    }]
],
"plugins": [
    [
        "module-resolver", {
            "alias": {
                "External": "../external"
            }
        }
    ],
    "@babel/plugin-proposal-decorators",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-proposal-export-default-from",
    "@babel/plugin-proposal-export-namespace-from",
    "@babel/plugin-proposal-class-properties"
]}

.babelrc for external

{
"presets": [
    "@babel/preset-react"
],
"plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-transform-runtime"
]}

I've created an example to detail my problem at:

https://gitlab.com/nerdyman/babel-7-external-import-broken


TL;DR I'm trying to import scripts from outside of a project's root directory but they don't get transpiled by Babel, the scripts from within the project do transpile.

like image 668
nerdyman Avatar asked Feb 28 '18 15:02

nerdyman


Video Answer


1 Answers

I've managed to fix this by following this comment.

The solution is:

  1. Move .babelrc in the main project to babel.config.js and make it a CommonJS module
  2. Add --ignore=node_modules when running babel-node from the main project

This still seems pretty hacky and Babel doesn't seem to acknowledge the ignore property within babel.config.js it must be specified as a flag.

Babel 7 appears to only allow imports within the directory the babel config is in, however explicitly setting the --ignore flag overrides this.

You can view my working demo and the diff of what I changed to get it working.

The issue is still open on GitHub so there may be a better solution in the future.

like image 166
nerdyman Avatar answered Nov 09 '22 18:11

nerdyman