'babel-node with typescript throws "Cannot use import statement outside a module" in command line
So, I saw many similar issues, but most of them refer to built code, and this one is actually a CLI script.
My command is:
node_modules/.bin/babel-node -x .js,.jsx,.ts,.tsx scripts/database/index.ts generate
And if it calls some code from node_modules (React Native related to be precise) it will throw the error.
I tried type: module but it caused even worse errors.
babel.config.js:
module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    '@babel/preset-flow',
  ],
  plugins: [
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-transform-flow-strip-types'],
    [
      require.resolve('babel-plugin-module-resolver'),
      {
        root: ['.'],
        extensions: [
          '.ios.js',
          '.android.js',
          '.js',
          '.ts',
          '.tsx',
          '.json',
          // '.png',
        ],
        alias: {
          app: ['./app'],
          'test/*': ['test/'],
          '@components': './app/components',
        },
      },
    ],
  ],
  sourceMaps: true,
};
tsconfig.json:
{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["ES2016"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmit": true,
    "resolveJsonModule": true,
    "strict": true,
    "target": "esnext",
    "baseUrl": "./",
    "paths": {
      "app/*": ["app/*"],
      "tests": ["tests/*"],
    },
    // ensure ignores node_modules
    "skipLibCheck": true,
    "preserveSymlinks": true,
    "typeRoots": ["./node_modules/@types"],
    "types": [
      "node",
      "@wdio/types",
      "webdriverio/async",
      // "@wdio/jasmine-framework",
      // "expect-webdriverio/jasmine",
      "jest"
    ]
  },
  // "include": [
  //   "src/*",
  //   "tests/*",
  // ],
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js",
    // isnores special cases
    "**/modules/**",
    "node_modules/react-native/**",
    "node_modules/@react-navigation/**",
  ]
}
Solution 1:[1]
remove "type": "module"
install @babel/register
in your very first line of code, add this linerequire('@babel/register')({ extensions: ['.js', '.jsx', '.ts', '.tsx'] })
npm script"start": "babel-node -x js,.jsx,.ts,.tsx -- src/app.ts"
update:
turn out that you can skip the whole @babel/register thing, what you are missing is a -- in your command
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | 
