TransWikia.com

Node.js ES6: Cannot use keyword 'await' outside an async function

Stack Overflow на русском Asked by Cat Grey on August 28, 2020

Пытаюсь компилировать typescript код в es6 модули ноды с помощью webpack (почему не tsc? потому что возможностей больше).

// webpack.config.сjs
const path = require('path')

module.exports = {
  mode: 'development',
  target: 'node',
  entry: ['./main.ts'],
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  module: {
  rules: [
      {
        test: /.tsx?$/,
        loader: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
};


// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2017",
    "module": "ESNext",
    "lib": ["ES2015"],
    "strict": true,
    "strictPropertyInitialization": false,
    "moduleResolution": "node",
    "baseUrl": ".",
     "paths": {
       "@root/*": ["./*"]
     },
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}


// package.json
{
  "name": "31_mycms2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/express": "^4.17.7",
    "@types/glob": "^7.1.3",
    "@types/node": "^14.6.0",
    "express": "^4.17.1",
    "glob": "^7.1.6",
    "module-alias": "^2.2.2",
    "reflect-metadata": "^0.1.13",
    "sqlite3": "^5.0.0",
    "ts-loader": "^8.0.2",
    "typeorm": "^0.2.25",
    "typescript": "^4.0.2"
  }
}


// main.ts
import { createConnection } from "typeorm";
export const orm = await createConnection({
    type: "sqlite",
    database: "db.sqlite",
    synchronize: true,
})

Но на этапе компиляции получаю ошибку:

Cannot use keyword 'await' outside an async function (файл main.ts строка 2)

Это странно, потому что es6 модули ноды поддерживают top-level await. Интересно то, что tsc main.ts ошибок не выдает.

One Answer

Вопрос решен. Обновил версию webpack до 5.0.0-beta и добавил в webpack.config.cjs:

module.exports = {
  //...
  experiments: {
    topLevelAwait: true
  }
}

Answered by Cat Grey on August 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP