1

Gruntfile で以下を使用しています。

grunt.initConfig({
    assets: grunt.option('assets'),
    config: grunt.file.readJSON(path.join('<%= assets %>', 'config.json')) || grunt.file.readJSON('./defaults.json'),
    ...
})

実行すると、次のようにスローされます。

>> Error: Unable to read "<%= assets %>/config.json" file (Error code: ENOENT).
    >> at Object.util.error (/.../prj/node_modules/grunt-legacy-util/index.js:54:39)
    >> at Object.file.read (/.../prj/node_modules/grunt/lib/grunt/file.js:247:22)
    >> at Object.file.readJSON (/.../prj/node_modules/grunt/lib/grunt/file.js:253:18)
    >> at Object.module.exports (/.../prj/Gruntfile.js:10:28)
    >> at loadTask (/.../prj/node_modules/grunt/lib/grunt/task.js:325:10)
    >> at Task.task.init (/.../prj/node_modules/grunt/lib/grunt/task.js:437:5)
    >> at Object.grunt.tasks (/.../prj/node_modules/grunt/lib/grunt.js:120:8)
    >> at Object.module.exports [as cli] (/.../prj/node_modules/grunt/lib/grunt/cli.js:38:9)
    >> at Object.<anonymous> (/usr/local/lib/node_modules/grunt-cli/bin/grunt:45:20)
    >> at Module._compile (module.js:425:26)

これは、assets使用しようとしている時点で var が定義されていないためでしょうか? または、 <%= %> 構文はこの方法で使用できませんか?

この答えによると、うまくいくはずです-以前は を使っていたので見つけましたvar assets = grunt.option('assets')が、それSyntaxError: Unexpected token varは何らかの理由で投げていました。(いじる前はこんな感じでした:)

module.exports = function(grunt) {
    require('load-grunt-tasks')(grunt)

    var util = require('util'),
        path = require('path'),
        pkg = require('./package.json')

    var assets = grunt.option('assets'),
    var config = grunt.file.readJSON(path.join(assets, 'config.json')) || grunt.file.readJSON('./defaults.json')

    grunt.initConfig({
        ...
    })

モジュールを使用したり、このように gruntfile 内で変数を宣言したりする適切でうなり声のある方法は何ですか? または、問題を解決できUnexpected token varますか?

(注:読み込みに問題があるのは構成ファイルではありません。アセットのパスgrunt.option()が解釈されていないように見えるためです)

4

3 に答える 3

1

カスタムjsonファイルを読みたいようです。grunt スクリプトでさえ単なる JavaScript であり、ノードは問題なく動作する必要があることを忘れないでください。だからあなたは次のようなことができます

 var conf = grunt.file.exists(assets + '/ '+ 'config.json') ? require(assets + '/ '+ 'config.json') : {};

configその後、どこでも変数を使用できます。

conf.foo || 'default'
conf.bar

どちらの場合も、assets使用する前に変数を宣言する必要があります。要求中または中initConfig

アップデート

また、
後に余分なコンマがあります。var assets = grunt.option('assets'),それを削除するかvar、次の行を削除します

于 2016-08-08T21:11:34.547 に答える
0

有効な JS 構文ではないため、中括弧var assets = ..内で宣言することはできません。grunt.init( {構文を理解するために必要なことは、次の<%= %>ように宣言することです。

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    uglify: {
        options: {
            banner: '/*! <%= pkg.name %>'
            // pkg is a property on the json object passed into initConfig
...
于 2016-08-08T21:07:00.533 に答える