Uncaught ReferenceError: define is not defined typescript

感情迁移 提交于 2019-12-19 05:06:09

问题


I am new to typescript, knockout and requirejs. I have created some demo using this files. Now, I want to implement some minor logic using typescript and knockoutjs.

I have created 4-5 typescript files, which are imported internally. When I run the html file. I am getting the error stating. as Titled

Can somebody help me on this error. What I am missing in this code.

have search on google and spend quite a good time but didn't find the proper solutions. It must be related to requireJS to define all modules. But, as new in requireJS not able to catch up with that. I have also search stackoverflow for the similar error, but it doesn't help me out.

Waiting for the solution


回答1:


Here your TypeScript has compiled happily, to code that will work in a requireJS environment (technically, an AMD environment). That means it generates output that assumes that define/require etc all already exist.

The overall answer is that you need to include RequireJS before you depend on your compiled code.

Notably the error suggests you've made a separate mistake though: you're depending directly on the RequireJS module scripts (i.e. you have a <script src="my-compiled-code.js"></script> tag in your HTML). That's not how require modules work. Instead, once you've made RequireJS available, you should have a single top-level startup script (either inline in your HTML or as a separate file) that configures RequireJS and then require()'s the top-level files of your application to start everything off. You can load this file either by hand, or with RequireJS's "data-main" attribute.

For example, a minimal HTML looks something like:

<!DOCTYPE html>
<html>
    <head>
        <script data-main="scripts/main" src="scripts/require.js"></script>
    </head>
    <body>
    </body>
</html>

This loads RequireJS from 'scripts/require.js' and then tells it to load the script at 'scripts/main.js' to start off the loading process (you'll probably want to update both paths - note that data-main doesn't need a .js extension).

The main script should then be something very simple like:

// Set up any config you need (you might not need this)
requirejs.config({
  basePath: "/scripts"
});

// Tell RequireJS to load your main module (and its dependencies)
require("mainmodule");

Generally, it's not TypeScript problems you're fighting here, it's RequireJS. I'd try spending a bit more time playing with just Require (maybe in pure JavaScript, so it's clearer) and looking at working examples for that, so you can get that bit working first, then add in the rest.



来源:https://stackoverflow.com/questions/38817636/uncaught-referenceerror-define-is-not-defined-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!