External imports in Babel 7 do not get transpiled

2020-06-09 11:00发布

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.

2条回答
smile是对你的礼貌
2楼-- · 2020-06-09 11:34

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.

查看更多
一纸荒年 Trace。
3楼-- · 2020-06-09 11:43

current directory's .babelrc won't be loaded while import files in external directory, you may place a .babelrc in that directory and set its presets by relative path(instead of short name):

{ "presets": ["..\pad\node_modules\babel-preset-env"], "retainLines": true }

查看更多
登录 后发表回答