我严重缺少了关于如何使用r.js优化器的一些重要元素。对许多人来说,这可能是一个微不足道的答案,但我可以为我的生活找出问题所在。 我使用grunt任务设置了我的环境来构建优化文件。优化的文件被构建并且依赖似乎可以正确解析,但是我的mainfile中的代码从未被执行。Requirejs优化文件未执行
我已经创建了一个最小的环境来帮助你在几乎只有Gruntfile,mainfile和一些依赖项(jquery,almond)的地方帮助我。
我的项目结构为:
require_this/
│
├──Gruntfile.coffee
│
└──src/
│
├──index.html
│
├──bower_components/(jquery,almond,requirejs)
│
└──app/
│
└──main.js
Gruntfile:
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'
]
的index.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 optimized main.js?(某些模块名称不匹配?),但我不明白这足以解决我自己的问题。
非常感谢帮助!