“unexpected token import” in Nodejs5 and babel?

前端 未结 13 2112
清酒与你
清酒与你 2020-11-30 18:40

In js file, i used import to instead of require

import co from \'co\';

And tried to run it directly by nodejs since it said import is \'shi

13条回答
  •  春和景丽
    2020-11-30 19:16

    It may be that you're running uncompiled files. Let's start clean!

    In your work directory create:

    • Two folders. One for precompiled es2015 code. The other for babel's output. We'll name them "src" and "lib" respectively.
    • A package.json file with the following object:

      { 
        "scripts": {
            "transpile-es2015": "babel src -d lib"
        },
        "devDependencies": {
            "babel-cli": "^6.18.0",
            "babel-preset-latest": "^6.16.0"
        }
      }
      
    • A file named ".babelrc" with the following instructions: {"presets": ["latest"]}

    • Lastly, write test code in your src/index.js file. In your case: import co from 'co'.

    Through your console:

    • Install your packages: npm install
    • Transpile your source directory to your output directory with the -d (aka --out-dir) flag as, already, specified in our package.json: npm run transpile-es2015
    • Run your code from the output directory! node lib/index.js

提交回复
热议问题