如何将导入与现有的 Node 应用程序一起使用?
How to use import with existing Node app?
对于 Node 16.13.2,我正在尝试添加 validate module in an existing code base. Reading the 我无法使其与以下 PoC 一起使用。我得到
import Schema from 'validate';
^^^^^^
SyntaxError: Cannot use import statement outside a module
问题
谁能告诉我下面的 PoC 应该是什么样子才能工作?
index.js
const mod = require('./mod');
mod.js
import Schema from 'validate';
const test;
module.exports = test;
如果你想使用 es6+
的 import
语法,那么你要么需要使用 .mjs
文件(而不是常规的 .js
文件),要么你将需要在您的管道中添加一个 compilation/transpilation 步骤。
使用.mjs
如果您将 mod.js
文件的文件名更改为 mod.mjs
,那么这应该有效:
import Schema form 'validate';
export const test;
然后在 index.js
中,您要么必须将 index.js
更改为 index.mjs
并将内容更改为:
import { test } from './mod.mjs';
..或者您可以保留 index.js
并将内容更改为:
(async () {
const { test } = await import('./mod.mjs')
})();
您可以在我在谷歌搜索时偶然发现的这篇相当全面的文章中阅读更多内容:https://blog.logrocket.com/how-to-use-ecmascript-modules-with-node-js/
添加一个编译步骤
有许多不同的编译器 and/or 打包器可供选择,但对于普通的香草 javascript 我建议坚持使用 babel。
Freecodecamp 有一个关于如何设置 babel 以与 nodejs 一起使用的教程:https://www.freecodecamp.org/news/setup-babel-in-nodejs/
对于 Node 16.13.2,我正在尝试添加 validate module in an existing code base. Reading the
import Schema from 'validate';
^^^^^^
SyntaxError: Cannot use import statement outside a module
问题
谁能告诉我下面的 PoC 应该是什么样子才能工作?
index.js
const mod = require('./mod');
mod.js
import Schema from 'validate';
const test;
module.exports = test;
如果你想使用 es6+
的 import
语法,那么你要么需要使用 .mjs
文件(而不是常规的 .js
文件),要么你将需要在您的管道中添加一个 compilation/transpilation 步骤。
使用.mjs
如果您将 mod.js
文件的文件名更改为 mod.mjs
,那么这应该有效:
import Schema form 'validate';
export const test;
然后在 index.js
中,您要么必须将 index.js
更改为 index.mjs
并将内容更改为:
import { test } from './mod.mjs';
..或者您可以保留 index.js
并将内容更改为:
(async () {
const { test } = await import('./mod.mjs')
})();
您可以在我在谷歌搜索时偶然发现的这篇相当全面的文章中阅读更多内容:https://blog.logrocket.com/how-to-use-ecmascript-modules-with-node-js/
添加一个编译步骤
有许多不同的编译器 and/or 打包器可供选择,但对于普通的香草 javascript 我建议坚持使用 babel。
Freecodecamp 有一个关于如何设置 babel 以与 nodejs 一起使用的教程:https://www.freecodecamp.org/news/setup-babel-in-nodejs/