问题描述:

My project structure is like this:

├── src

| ├── js

| └── a.js

├── test

| ├── spec

| └── test_a.js

My a.js looks like this:

define('A/B/C', function(){

var D = ...

return D;

})

In my karma.conf.js, I have include requirejs in frameworks, and the needed files are included as follows:

files: [

{pattern: 'src/js/*.js', included: false},

{pattern: 'test/spec/*.js', included: false},

'test/test-bootstrap.js'

]

And my test_a.js looks like:

define(['A/B/C'], function(D){

//test case

})

But the browser looks for localhost:9876/base/A/B/C.js and returns an error because only localhost:9876/base/src/js/a.js exists in browser.

My question is, since src/js/a.js is loaded already, and I introduce requirejs in karma.conf.js, why couldn't the module loaded by its id? Did I write the A/B/C module in wrong way?

My require.config in test/test-bootstrap.js is:

require.config({

// Karma serves files under /base, which is the basePath from your config file

baseUrl: 'http://localhost:9876/base',

paths: {

'jquery': 'test/lib/jquery-1.12.0.min'

},

// dynamically load all test files

deps: allTestFiles,

// we have to kickoff jasmine, as it is asynchronous

callback: window.__karma__.start

});

I need to load module by its id because I may change my project structures and I don't want the module path is hard coded into test file.

网友答案:

You have to configure RequireJS to find your module because you gave it a name that does not correspond to a path that RequireJS can use. In general, it is not advisable to hard code names in modules but if you do have a good reason, then in the part of test/test-bootstrap.js that calls require.config, you should have a paths like this:

paths: {
    'A/B/C': 'src/js/a',
    // and whatever else you'd need...
}
相关阅读:
Top