Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

javascript - 在脚本中导入类(Importing classes in script)

I have a flask app with the following file located in static/js/foo.js :(我有一个flask应用程序,其中以下文件位于static / js / foo.js中 :)

export default class Foo { constructor(message) { this.message = message; } toString() { return `${this.message}`; } } In my templates/index.html file, I'm trying to create an instance of Foo as follows:(在我的templates / index.html文件中,我尝试如下创建Foo的实例:) <script src="{{ url_for('static', filename='js/foo.js') }}" type="module"></script> <script> let foo = new Foo('hello foo!'); console.log(`${foo}`); </script> However, I'm getting the following error in the console: Uncaught ReferenceError: Foo is not defined .(但是,我在控制台中收到以下错误: Uncaught ReferenceError:Foo未定义 。) Is there a simple way to use a class defined in another file, ie Foo from within foo.js ?(有没有简单的方法可以使用在另一个文件(即foo.js中的 Foo定义的类?)   ask by alex_lewis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make your inline script a module as well, and import Foo from foo.js :(您还需要将内联脚本作为模块,并从foo.js导入Foo:)

<!-- This is not required <script src="{{ url_for('static', filename='js/foo.js') }}" type="module"></script> --> <script type="module"> import Foo from "{{ url_for('static', filename='js/foo.js') }}"; let foo = new Foo('hello foo!'); console.log(`${foo}`); </script> From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules :(从https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules中 :) Last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope.(最后但并非最不重要的一点,我们要弄清楚-模块功能已导入单个脚本的作用域-它们在全局作用域中不可用。) Therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the JavaScript console, for example.(因此,例如,您将只能在脚本中访问导入的功能,而无法从JavaScript控制台访问它们。) You'll still get syntax errors shown in the DevTools, but you'll not be able to use some of the debugging techniques you might have expected to use.(您仍然会在DevTools中看到语法错误,但是您将无法使用您可能希望使用的某些调试技术。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...