我的應用程式運行良好,但我無法將我的隔離函式從 utils.ts 檔案匯入到測驗檔案中。錯誤資訊:(SyntaxError: Cannot use import statement outside a module螢屏下方)
我整天絞盡腦汁,看過很多教程和檔案,但我還沒有找到任何解決方案。我想解決它,所以我不是必須在編程時打開運行控制臺。這只是普通的 JS HTML CSS,我不喜歡使用npm init.
我也經歷了許多類似的 stackoverflow 問題,但沒有任何效果,例如我不能添加type: module到 package.json 中,因為它會導致我的應用程式中出現另一個錯誤。
拜托,有人可以幫我在哪里犯錯嗎?
索引.html:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button id="startAppBtn">start</button>
<div id="container" class="container">
<div id="pointsBox" class="pointsBox"></div>
</div>
<script type="module" src="index.js" defer></script>
</body>
</html>
index.js
import { InsertionSort } from "./insertionSort.js";
const algo = new InsertionSort();
const startAppBtn = document.getElementById("startAppBtn");
startAppBtn.addEventListener('click', () => {
console.log('start app');
algo.mainApp(); /* all app is executed here inside this method, it contains
around 300 lines, so i didn't attache all the code inside, i don't
think it is important. */
});
實用程式.js
import Point from './point.js'; // => here it fails, this import evaluates testing file as error
export function xxx() {
new Point(i, value[0] 1);
return 'xxx';
}
util.test.js
var assert = require('assert');
var { xxx } = require('./utils'); // here I import method from utils
describe('Array', function () {
describe('#xxx', function () {
it('import test', function () {
const res = xxx(); // here it is used
assert.equal('xxx', res);
});
});
});
包.json
{
"devDependencies": {
"jest": "^28.0.3"
}
}
螢屏:

uj5u.com熱心網友回復:
盡管您的示例中有很多東西可能會出錯(因為有很多東西有很多失敗點),但我會猜測 - 因為它很有趣。
我看到您使用的測驗檔案require(),所以這些是 CommonJS 模塊。您的實際代碼使用匯入/匯出,因此這些是 ES Moules。你不能只是混合它們。除非您將 jest 配置為使用 babel 將您的源代碼轉換為 CommonJS 模塊,否則這是行不通的。笑話檔案包含所有命令。將 babel 配置為針對當前節點版本進行轉換就足夠了。
如果您只在代碼庫中使用 ES 模塊,您可以將測驗代碼更改為也使用 ES 模塊。檢查您的 jest 配置,因為您可能需要告訴 jest 使用 ES 模塊而不是 CommonJS。 支持仍處于試驗階段,但您可以試一試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470387.html
