“unexpected token import” in Nodejs5 and babel?

前端 未结 13 2138
清酒与你
清酒与你 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:09

    I have done the following to overcome the problem (ex.js script)

    problem

    $ cat ex.js
    import { Stack } from 'es-collections';
    console.log("Successfully Imported");
    
    $ node ex.js
    /Users/nsaboo/ex.js:1
    (function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
                                                                  ^^^^^^
    
    SyntaxError: Unexpected token import
        at createScript (vm.js:80:10)
        at Object.runInThisContext (vm.js:152:10)
        at Module._compile (module.js:624:28)
        at Object.Module._extensions..js (module.js:671:10)
        at Module.load (module.js:573:32)
        at tryModuleLoad (module.js:513:12)
        at Function.Module._load (module.js:505:3)
        at Function.Module.runMain (module.js:701:10)
        at startup (bootstrap_node.js:194:16)
        at bootstrap_node.js:618:3
    

    solution

    # npm package installation
    npm install --save-dev babel-preset-env babel-cli es-collections
    
    # .babelrc setup
    $ cat .babelrc
    {
      "presets": [
        ["env", {
          "targets": {
            "node": "current"
          }
        }]
      ]
    }
    
    # execution with node
    $ npx babel ex.js --out-file ex-new.js
    $ node ex-new.js
    Successfully Imported
    
    # or execution with babel-node
    $ babel-node ex.js
    Successfully Imported
    

提交回复
热议问题