简体   繁体   English

是否可以使用节点命令将 node.js 脚本作为模块运行(不使用 package.json)?

[英]Is it possible to run a node.js script as a module with the node command (without using package.json)?

Let's say I have a code.js file with the following node.js script:假设我有一个包含以下 node.js 脚本的code.js文件:

const axios = require('axios')

async function getData(){
    const response = await axios.get('https://mypage.com.br')
    console.log(response.data)
}
getData()

If I execute it with node code.js it works perfectly fine... However, I'd like to execute it as a module, just so I can use the import statement and use the await command as top level.如果我使用node code.js执行它,它工作得很好......但是,我想将它作为一个模块执行,这样我就可以使用import语句并将await命令用作顶层。 I'd like to accomplish that without creating a project with a package.json file.我想在不使用package.json文件创建项目的情况下完成此操作。 My final result would be something like this:我的最终结果是这样的:

import axios from 'axios' 

const response = await axios.get('https://mypage.com.br')
console.log(response.data)

I haven't managed to make it work with the node command.我还没有设法让它与node命令一起工作。 I know there's a --input-type=module parameter I can use with it.我知道我可以使用一个--input-type=module参数。 But I've tried running node --input-type=module code.js and I've received the following error:但是我尝试运行node --input-type=module code.js并且收到以下错误:

SyntaxError: Cannot use import statement outside a module

So, that means it's not even being recognized as a module yet.所以,这意味着它甚至还没有被识别为一个模块。 Is it possible to do?有可能吗? Can I execute an isolated script with the command node as a module (while using await on top level)?我可以将命令node作为模块执行一个独立的脚本吗(在顶层使用await时)?

Rename the file to name.mjs .将文件重命名为name.mjs This --input-type parameter only applies to STDIN and --eval -d files.--input-type参数仅适用于 STDIN 和--eval -d 文件。

This isn't really possible from the command line.这在命令行中是不可能的。 You have only two options for making your file ESM.您只有两个选项来制作文件 ESM。

  1. Edit package.json to have the following key and value.编辑package.json以具有以下键和值。

     { "type": "module" }
  2. Change the file extensions from .js to .mjs .将文件扩展名从.js更改为.mjs The m stands for module . m代表模块

In conclusion, the flag below doesn't help with changing the type to module.总之,下面的标志无助于将类型更改为模块。

$ node code.js --input-type=module

A different alternative without renaming the file is executing the code with a pipe .另一种不重命名文件的替代方法是使用pipe执行代码。 The following command works fine as a module:以下命令作为模块运行良好:

cat code.js | node --input-type=module

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM