我嚴重缺少了關於如何使用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?(某些模塊名稱不匹配?),但我不明白這足以解決我自己的問題。
非常感謝幫助!