【发布时间】:2019-06-04 07:18:46
【问题描述】:
我想在 django 的 index.html 中使用 ES6 中的导入功能。
为了浏览器兼容性,我不想编译为 ES5。我想假设所有用户都将拥有 ES6 兼容的浏览器。
因此我不需要像 Babel 这样的 ES6 到 ES5 编译器:https://github.com/kottenator/django-compressor-toolkit
如果可以的话,我只是想提供 ES6 Javascript 和浏览器来编译它。
我试过了:
<!-- Index.html -->
<script type="module" src="{% static 'app.js' %}"></script>
//app.js
(function(){
console.log("Hello from App.js");
})();
# settings.py
if DEBUG:
import mimetypes
mimetypes.add_type("module", ".js", True)
我得到的错误:
加载模块脚本失败:服务器以“text/plain”的非 JavaScript MIME 类型响应。根据 HTML 规范对模块脚本强制执行严格的 MIME 类型检查。
更新 1: 我试过了:
<script type="module" src="{% static 'app.js' %}"></script>
<script nomodule src="{% static 'app.js' %}"></script>
<script type="module">import "{% static 'main.mjs' %}";</script>
https://developers.google.com/web/fundamentals/primers/modules
更新 2:是否可以不使用预编译器?
https://github.com/kottenator/django-compressor-toolkit
更新 3:我找到了
https://module-script-tests-sreyfhwvpq.now.sh/mime
我使用 Chrome: 谷歌浏览器是最新的 版本 71.0.3578.98(正式版)(64 位)
更新 4: 我想使用
<!-- index.html -->
<script type="module"> instead of <script type="text/javascript">
因为我希望能够导入模块:
<!-- index.html -->
<script type="application/javascript" src="{% static 'app.js' %}"></script>
//app.js
import { print } from "{% static 'component.js' %}"
目前报错:
Uncaught SyntaxError: Unexpected token {
更新 5:
这是我的文件结构:
这是我的索引:
{% extends 'base.html' %}
{% block content %}
{% load static from staticfiles %}
<h1>Index</h1>
{% include 'component.html' %}
<script type="module" src="{% static 'app.js' %}"></script>
{% endblock %}
这是我的 base.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Index</title>
{% load static from staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>
这是我的 app.js:
import {A} from "./component.js"
console.log("A" + A)
这是我的 component.js:
export const A = 42
这是我仍然得到的错误:
加载模块脚本失败:服务器以“text/plain”的非 JavaScript MIME 类型响应。根据 HTML 规范对模块脚本强制执行严格的 MIME 类型检查。
这是我得到的内容类型:
【问题讨论】:
-
django-compressor-toolkit允许您在 Django 项目中启用 ES6。我使用这个项目启用 ES6。 -
是的,但是压缩器工具包用于将 ES6 转换为 ES5。我不应该在现代浏览器中转换它吗?我想简单地运行 ES6 html 代码。
标签: django ecmascript-6 django-templates es6-modules django-staticfiles