這個問題在這里已經有了答案: Node.js - SyntaxError: Unexpected token import (16 answers) 1 小時前關閉。
對于 Node 16.13.2,我正在嘗試在現有代碼庫中添加驗證模塊。閱讀2 歲的問題,我無法使其與以下 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;
uj5u.com熱心網友回復:
如果你想使用 then 的import語法,es6 你要么需要使用.mjs檔案(而不是常規.js檔案),要么需要在管道中添加編譯/轉譯步驟。
使用 .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/
添加編譯步驟
有許多不同的編譯器和/或捆綁器可供選擇,但對于常規的香草 javascript,我建議堅持使用babel。
Freecodecamp 有一個關于如何設定 babel 以與 nodejs 一起使用的教程:https ://www.freecodecamp.org/news/setup-babel-in-nodejs/
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410919.html
標籤:
