我严重错过了有关如何使用 r.js 优化器的一些重要元素。对于许多人来说,这可能是一个微不足道的答案,但我可以终生无法解决这个问题。我已经使用 grunt 任务设置了我的环境来构建优化的文件。优化的文件已构建并且依赖项似乎可以正确解析,但我的主文件中的代码从未执行过。
我创建了一个最小环境来帮助您帮助我,其中几乎只有 Gruntfile、主文件和一些依赖项(jquery、almond)。
我的项目结构是:
require_this/
│
├──Gruntfile.coffee
│
└──src/
│
├──index.html
│
├──bower_components/(jquery,almond,requirejs)
│
└──app/
│
└──main.js
咕噜文件:
module.exports = (grunt) ->
'use strict'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
settings:
distDirectory: 'dist'
srcDirectory: 'src'
tempDirectory: '.temp'
allFile: 'main.js'
clean:
working: ['<%= settings.tempDirectory %>', '<%= settings.distDirectory %>']
finished: ['<%= settings.tempDirectory %>']
copy:
app:
files: [
cwd: '<%= settings.srcDirectory %>'
src: '**'
dest: '<%= settings.tempDirectory %>'
expand: true
]
requirejs:
scripts:
options:
baseUrl: '<%= settings.tempDirectory %>'
mainConfigFile: '<%= settings.tempDirectory %>/app/main.js'
optimize: 'none'
logLevel: 0
findNestedDependencies: true
name: 'main'
include: ['requireLib']
paths:
'main': 'app/main'
'requireLib': 'bower_components/almond/almond'
out: '<%= settings.distDirectory %>/<%= settings.allFile %>'
processhtml:
your_target:
files:
'dist/index.html': '.temp/index.html'
grunt.loadNpmTasks 'grunt-processhtml'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-copy'
grunt.loadNpmTasks 'grunt-contrib-requirejs'
grunt.registerTask 'build', [
'clean:working'
'copy:app'
'requirejs'
'processhtml'
]
索引.html:
<!DOCTYPE html>
<head>
<!-- build:js main.js -->
<!-- The line below will be changed to <script src="main.js"></script> after processhtml -->
<script src="bower_components/requirejs/require.js" data-main="app/main.js"></script>
<!-- /build -->
</head>
<body>
</body>
main.js
require.config({
baseUrl: './',
paths: {
'jquery': 'bower_components/jquery/dist/jquery.min'
}
});
define([
'jquery',
], function ($) {
console.log('changing html');
$('body').append('<div>Hello World</div>');
});
完成构建任务后,我的 dist 目录将包含 index.html 和 main.js 文件。dist/main.js 文件将如下所示:
/*almond stuff*/
/*jquery stuff*/
require.config({
baseUrl: './',
paths: {
'jquery': 'bower_components/jquery/dist/jquery.min'
}
});
define('main',[
'jquery',
], function ($) {
console.log('changing html');
$('body').append('<div>Hello World</div>');
});
对未压缩文件使用静态文件服务器可以按预期工作。使用构建文件时,即使加载了优化文件,也不会记录任何内容,也不会将任何内容添加到 html 中。
我怀疑答案类似于Why is my RequireJS ignoring the code in my optimization main.js? , (某些模块名称不匹配?)但我对此的理解不足以解决我自己的问题。
非常感谢您的帮助!