好吧,我想我有一個解決方法。假設您希望構建的文件也指向構建資產的靜態url。
這將要求您在視圖上下文中定義STATIC_URL(而不是使用src="{% static 'foo/bar.js' %}"
,您將使用src="{{STATIC_URL}}foo/bar.js"
)。我無法讓{% static %}
工作,而無需攻擊grunt-usemin源代碼。
所以使用您的例子,這樣的:
<!-- build:js {{STATIC_URL}}scripts/scripts.js -->
<script src="{{STATIC_URL}}scripts/app.js"></script>
<script src="{{STATIC_URL}}scripts/controllers/main.js"></script>
<script src="{{STATIC_URL}}scripts/controllers/stats.js"></script>
<script src="{{STATIC_URL}}scripts/directives/highchart.js"></script>
<!-- endbuild -->
編譯爲:
<script src="{{STATIC_URL}}scripts/scripts.js"></script>
爲了實現這一點,我不得不添加以下咕嚕配置(在Gruntfile.js):
// custom createConfig script for replacing Django {{STATIC_URL}} references
// when building config for concat and cssmin
var path = require('path');
function createDjangoStaticConcatConfig(context, block) {
var cfg = {files: []};
var staticPattern = /\{\{\s*STATIC_URL\s*\}\}/;
block.dest = block.dest.replace(staticPattern, '');
var outfile = path.join(context.outDir, block.dest);
// Depending whether or not we're the last of the step we're not going to output the same thing
var files = {
dest: outfile,
src: []
};
context.inFiles.forEach(function(f) {
files.src.push(path.join(context.inDir, f.replace(staticPattern, '')));
});
cfg.files.push(files);
context.outFiles = [block.dest];
return cfg;
}
grunt.initConfig({
/*...*/
// add a preprocessor to modify the concat config to parse out {{STATIC_URL}} using the above method
useminPrepare: {
html: 'app/index.html',
options: {
dest: 'dist',
flow: {
steps: {
js: [
{
name: 'concat',
createConfig: createDjangoStaticConcatConfig
},
'uglifyjs'
],
// also apply it to css files
css: [
{
name: 'cssmin',
createConfig: createDjangoStaticConcatConfig
}
]
},
// this property is necessary
post: {}
}
}
},
// add a pattern to parse out the actual filename and remove the {{STATIC_URL}} bit
usemin: {
html: ['dist/{,*/}*.html'],
css: ['dist/styles/{,*/}*.css'],
options: {
assetsDirs: ['dist'],
patterns: {
html: [[/\{\{\s*STATIC_URL\s*\}\}([^'"]*)["']/mg, 'django static']]
}
}
},
// if you are using bower, also include the jsPattern to automatically
// insert {{STATIC_URL}} when inserting js files
'bower-install': {
app: {
html: 'app/index.html',
jsPattern: '<script type="text/javascript" src="{{STATIC_URL}}{{filePath}}"></script>'
}
}
});
你是否用'grunt build'構建了這個站點,不應該爲客戶端提供一個usemin塊,這隻適用於咕嚕聲,並且與後端(afaik)無關。 – Patrick
我試圖利用Django的反向URL查找靜態url,所以我從Django路徑提供Angular的index.html,這允許我在index.html中使用Django模板標籤。我已經放棄了這一點,現在將從靜態url訪問index.html,而不是正確的Django路線。我會咬緊牙關,如果我的靜態文件網址發生變化,我會手動更新index.html。 – davemckenna01
@ davemckenna01自8月份起,當您最初提問時,您是否發現過任何新內容?我目前正在使用grunt/yeoman和Angular,並且將工作流程與django集成在一起會讓我放慢腳步。 – kevins