【问题标题】:document.getElementById("app").innerHTML fails when using imports使用导入时 document.getElementById("app").innerHTML 失败
【发布时间】:2020-06-03 21:22:11
【问题描述】:

第一个 Js 文件(testtest.js):

let test = "<h1>hello</h1>";
module.exports = test;

第二个Js文件:

const test = require('./testtest');
document.getElementById("app").innerHTML = "<h1>hello</h1>";

当我在使用导入时尝试使用 document.getElementById("app").innerHTML 时,它无法显示 HTML,但是,如果我评论 import 行,它会按预期工作。

你能帮忙解决问题吗?

【问题讨论】:

  • 你的意思是写 document.getElementById("app").innerHTML = test;

标签: javascript html css web


【解决方案1】:

这看起来像是服务器端 js 和客户端 js 的组合。客户端 js 不使用module.exports 或require。 Ofc 你可以使用捆绑器,但根据帖子我不认为你是。

文件:testtest.js

let test = "<h1>hello</h1>";
export default test;

第二个js文件:

//this import must be top level
import test from "./testtest.js";
document.getElementById("app").innerHTML = test;

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import

【讨论】:

  • 使用 Es6 导入导出语法引发语法错误:
  • 使用 es6 语法导入和导出默认会引发语法错误:PS C:\test> node rendertextindex.js C:\test\rendertextindex.js:1 import test from "./testtest.js" ; ^^^^^^ SyntaxError: Cannot use import statement outside a module?[90m at Module._compile (internal/modules/cjs/loader.js:891:18)?[39m ?[90m at Object.Module._extensions。 .js (internal/modules/cjs/loader.js:991:10)?[39m
  • 确保你的脚本标签中有type="module",所以&lt;script type="module"&gt;&lt;/script&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
相关资源
最近更新 更多