[英]babel-node with typescript throws "Cannot use import statement outside a module" in command line
所以,我看到了很多类似的问题,但大多数都是指构建代码,而这个实际上是一个 CLI 脚本。
我的命令是: node_modules/.bin/babel-node -x.js,.jsx,.ts,.tsx scripts/database/index.ts generate
如果它从node_modules
(准确地说是React Native
相关)调用一些代码,它将抛出错误。
我试过type: module
但它导致了更严重的错误。
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/**",
]
}
删除"type": "module"
安装@babel/register
在您的第一行代码中,添加这一行require('@babel/register')({ extensions: ['.js', '.jsx', '.ts', '.tsx'] })
npm 脚本"start": "babel-node -x js,.jsx,.ts,.tsx -- src/app.ts"
更新:
原来你可以跳过整个@babel/register
事情,你缺少的是--
在你的命令
哇,这太粗糙了。
我最近开始逐渐在我的 Node 应用程序中采用 TS,我认为这就是原因。
但我开始认为babel-node
中--config
的默认选项不再寻找babel.config.js
而只是寻找babel.config.json
。
我煞费苦心地将我的 babel 配置转换为 JSON,这似乎已经修复。
此外,-- --extensions
参数必须包含.ts
。 因此,要在同一项目中同时支持.js
和.ts
文件,您需要定义以下内容:
package.json
"scripts": {
"task": "babel-node --extensions .js,.ts -- ",
}
babel.config.json
{
"presets": [
"@babel/preset-typescript",
[
"@babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
],
"plugins": [
[
"module-resolver",
{
"root": ["./"],
"alias": {
"test": "./__test__"
}
}
]
]
}
最后我能够像这样执行 CLI 命令:
yarn task something.js
或者
yarn task something.ts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.