首页 > 解决方案 > 运行连接到 MongoDB 云集群的 nodejs 应用程序时,Docker-compose 给出:“node|SyntaxError: Unexpected token import”错误

问题描述

我有一个在云上使用 MongoDb 集群的工作 nodejs 应用程序。我正在尝试使用 docker-compose up 对其进行 dockerize,但我不断收到此错误:

nodejs |从 'mongodb' 导入 Mongodb; 节点 | ^^^^^^ nodejs | SyntaxError:意外的令牌导入

这是我的 dockerFile:

FROM node:12.16.1 as build
WORKDIR /app
COPY . /app
RUN npm install
RUN npm run build
COPY . .
EXPOSE 80
CMD ["node", "app.js", "daemon off;"]

这是我的 docker-compose.yml:

version: '3'

services:
  nodejs:
    build:
      context: .
      dockerfile: Dockerfile
    image: nodejs
    container_name: nodejs
    restart: unless-stopped
    env_file: .env
    volumes:
      - node_modules:/node_modules
    command: node app.js 

  
volumes:
    node_modules:

这是我的 package.JSON 文件:

{
  "type": "module",
  "name": "krakenchallenge",
  "version": "1.0.0",
  "description": "A Node.js app that will filter out valid transactions from given JSON files containging a list of transactions returned from running bitcoind’s rpc call `listsinceblock`. The app is configured to allow working  with both SQL or mongoDB types.",
  "main": "index.js",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/abuaesh/KrakenChallenge.git"
  },
  "keywords": [
    "node",
    "js",
    "mongodb",
    "sql",
    "nosql",
    "bitcoin",
    "transaction",
    "deposit"
  ],
  "author": "Noha Abuaesh <noha.abuaesh@gmail.com>",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/abuaesh/KrakenChallenge/issues"
  },
  "homepage": "https://github.com/abuaesh/KrakenChallenge#readme",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": {
    "@babel/cli": "^7.0.0-beta.46",
    "@babel/core": "^7.10.4",
    "@babel/plugin-proposal-class-properties": "^7.0.0-beta.46",
    "@babel/plugin-proposal-object-rest-spread": "^7.0.0-beta.46",
    "@babel/preset-env": "^7.10.4",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.1.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "bitcoin-address-validation": "^1.0.2",
    "dotenv": "^8.2.0",
    "fs": "0.0.1-security",
    "mongodb": "^3.6.0",
    "wallet-address-validator": "^0.2.4"
  },
  "devDependencies": {
    "nodemon": "^1.18.10"
  }
}

标签: node.jsmongodbimportdocker-composees6-modules

解决方案


从版本13.2.0 开始支持该import语句浏览器兼容性表

或者从版本 12.0.0 开始,用户必须使用--experimental-modules运行时标志显式启用此功能。

确保重建您的图像。docker-compose up --build将在启动容器之前构建您的图像。


推荐阅读