我刚刚了解了JS中的模块。我正在尝试在我的机器上执行此操作,但仍然有几个问题,因为它仅在某些情况下有效。
我已经看过并尝试过使用以下语法的youtube视频示例:
// number.js
export const num = 5;
// main.js
import { num } from './number.js'
//This throws the following error:
import { num } from './number.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:1072:16)
at Module._compile (internal/modules/cjs/loader.js:1122:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
就我而言,它只有在执行以下操作时才有效:
// number.js
const num = 10;
module.exports = { num };
// main.js
const num = require('./number.js');
谁能启发我并告诉我有什么区别,并且从技术上讲我在做什么是正确的?
提前致谢!
您的export
和import
声明都很好,只是环境不知道这main.js
意味着要成为一个模块。
如果您要在Node.js上执行此操作,请参阅其文档以了解详细信息,但是简短版本可以放在"type": "module"
您的文件中,也可以package.json
使用扩展名.mjs
。
如果您是在浏览器上执行此操作,则script
该main.js
文件的标记必须具有,type="module"
以便JavaScript引擎知道它是一个模块。这是CodeSandbox上的一个实时示例。:
index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script src="./main.js" type="module"></script>
<title>Export / Import Example</title>
</head>
<body></body>
</html>
main.js
:
import { num } from "./number.js";
document.body.appendChild(document.createTextNode(`num = ${num}`));
number.js
:
export const num = 5;
(请注意,由于会type="module"
自动延迟脚本,因此无需body
像使用非模块脚本一样将其放在底部。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句