Requirejs - why the module is loaded in define (), but in require () is not

The code hit does not work and the error message:

Unprepared error: module name "text! Templates / bookTemplate.html_unnormalized2" is not loaded but for context: _. Use require ([])

define(['backbone', 'underscore', 'jquery'], function (Backbone, _, $) { var bt = require('text!templates/bookTemplate.html'); var BookView = Backbone.View.extend({ initialize: function () { this.render(); }, render: function () { var template = _.template(bt, { name: 'secret book' }); this.$el.html(template); } }); return BookView; }); 

then I move "text! templates / bookTemplate.html" to define (), it works! Below is the working code:

  define(['backbone', 'underscore', 'jquery', 'text!templates/bookTemplate.html'], function (Backbone, _, $, bt) { // var bt = require('text!templates/bookTemplate.html'); var BookView = Backbone.View.extend({ initialize: function () { this.render(); }, render: function () { var template = _.template(bt, { name: 'secret book' }); console.info('template', template); this.$el.html(template); } }); return BookView; }); // it is working 

As I understand it, require () and define () are the same when loading the module. It's right? Can you help me explain why it works in the definition and does not require require ()?

0
source share
1 answer

You call require string literal. When you call require as follows, it acts in pseudo-synchronous mode . It acts like a synchronous call because it will immediately return the module. It is pseudo-synchronous because the module must be loaded before you call the pseudo- require form.

So you can do this:

 define(['backbone', 'underscore', 'jquery', 'text!templates/bookTemplate.html'], function (Backbone, _, $) { var bt = require('text!templates/bookTemplate.html'); 

and this will work because the module will be loaded before require executed. Or you can use the method that you specified in the second code snippet:

 define(['backbone', 'underscore', 'jquery', 'text!templates/bookTemplate.html'], function (Backbone, _, $, bt) { 

Or you can use the CommonJS wrapper:

 define(function(require, exports, module) { var Backbone = require('backbone'); var _ = require('underscore'); var jquery = require('jquery'); var bt = require('text!templates/bookTemplate.html'); 

This wrapper works because RequireJS converts it at runtime to:

 define(["require", "exports", "module", "backbone", "underscore", "jquery", "text!templates/bookTemplate.html"], function(require, exports, module) { var Backbone = require('backbone'); var _ = require('underscore'); var jquery = require('jquery'); var bt = require('text!templates/bookTemplate.html'); 

before executing the module.

+1
source

Source: https://habr.com/ru/post/1236175/


All Articles