chrisbateman / webpack-visualizer

Visualize your Webpack bundle
http://chrisbateman.github.io/webpack-visualizer/
MIT License
1.69k stars 93 forks source link

Uncaught SyntaxError: Unexpected token p #6

Closed adjavaherian closed 8 years ago

adjavaherian commented 8 years ago

Any idea what might be causing this?

All I see in the chrome console is this when I load the stats.html

Uncaught SyntaxError: Unexpected token p(anonymous function) @ stats.html:165

Output looks pretty normal, but I do have a very complex config.

//webpack.config.js
//main webpack config
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var WebpackStrip = require('strip-loader');
var CachePlugin = require('webpack/lib/CachePlugin');
var PassthruPlugin = require('./webpack-utils/passthru-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var NyanProgressPlugin = require('nyan-progress-webpack-plugin');
var ProgressPlugin = require('./webpack-utils/progress-plugin');
var Visualizer = require('webpack-visualizer-plugin');
var RewirePlugin = require('rewire-webpack');
var StatsPlugin = require('stats-webpack-plugin');
var AssetsPlugin = require('assets-webpack-plugin');
var nodeCDN = process.env.NODE_ENV === 'production' ? '//nodecdn.dslam.com/dist/' : '/dist/';
var lifterParams = '?testString=scss&prefix=dist/images&manifest=rev-manifest&outputDir=' + path.join(__dirname, 'public', 'dist');  // add &outputStyle=compressed for prod
var manifestParams = {
    debug: false,
    limit: 5000,
    hash: 'sha512',
    digest: 'hex',
    relativeSplit: 'images/',
    prefix: nodeCDN +'images',
    manifest: 'rev-manifest',
    outputDir: path.join(__dirname, 'public', 'dist')
};
var DeepMerge = require('deep-merge');
var consoleAvailable = (process.argv.indexOf('--profile') === -1 &&
    process.env.NODE_ENV !== 'production' &&
    process.env.NODE_ENV !== 'integration');
var node_modules_dir = path.join(__dirname, 'node_modules');
var deps = [
    'velocity-animate/velocity.min.js',
    'mobile-detect/mobile-detect.min.js',
    'numeral/min/numeral.min.js'
];

var myCache = {};
var productionPlugins = [
    new webpack.optimize.UglifyJsPlugin({
        output: {
            comments: false
        }
    })
];
var productionLoaders = [
    { test: /\.js$/, loader: WebpackStrip.loader('debug', 'console.log') }
];

var deepmerge = DeepMerge(function(target, source, key) {
    if (target instanceof Array) {
        return [].concat(target, source);
    }
    return source;
});

function config(overrides) {
    return deepmerge(defaults, overrides || {});
}

//require common.js for node_modules (better for server)
var node_modules = fs.readdirSync('node_modules').filter(function(x) { return x !== '.bin' });
function node_externals(context, request, cb) {
    if (node_modules.indexOf(request) !== -1) {
        cb(null, 'commonjs ' + request);
        return;
    }
    cb();
}

//require common.js for configs, manifests that might change
var dist_dir  = fs.readdirSync(path.join(__dirname, 'public', 'dist')).filter(function(x) {
    if (x.indexOf('.json') > -1) {
        return x
    }
});

var config_modules  = ['states-json.json'].concat(dist_dir);

function config_externals(context, request, cb) {
    var clean_request = request.split('/').splice(-1)[0];
    if (config_modules.indexOf(clean_request) !== -1) {
        cb(null, 'commonjs ' + request);
        return;
    }
    cb();
}

var test = {
    name: 'karma webpack',
    devtool: 'eval',
    target: 'web',
    node: {
        __dirname: true,
        __filename: true,
        fs: 'empty',
        tls: 'empty',
        net: 'empty',
        module: 'empty',
        console: true
    },
    module: {
        unknownContextRegExp: /$^/,
        exprContextRegExp: /$^/,
        unknownContextCritical: false,
        exprContextCritical: false,
        loaders: [
            {
                test: /\.json$/,
                loaders: ['json-loader']
            }
            , {
                include: [
                    path.resolve(__dirname, 'app'),
                    path.resolve(__dirname, 'test')
                ],
                test: /\.jsx$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'stage-0', 'react']
                }
            }, {
                test: /\.scss$/,
                loader: 'noop-loader'
            }
            , {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loaders: [
                    'passthru-loader'
                ]
            }
            , {
                test: /sinon.*\.js$/,
                loader: 'imports?define=>false'
            }
        ],
        postLoaders: [ { // << add subject as webpack's postloader
            test: /\.js$/,
            exclude: /(test|node_modules|bower_components)\//,
            loader: 'istanbul-instrumenter'
        } ]
    },
    resolve: {
        root: path.join(__dirname),
        fallback: path.join(__dirname, 'node_modules'),
        modulesDirectories: ['app', 'images', 'node_modules'],
        extensions: ['', '.json', '.js', '.jsx', '.scss', '.png', '.jpg', '.jpeg', '.gif']
    },
    resolveLoader: {
        root: __dirname,
        fallback: __dirname + '/node_modules',
        alias: {
            'noop-loader': path.join(__dirname,  'webpack-utils', 'noop-loader'),
            'passthru-loader': path.join(__dirname, 'webpack-utils', 'passthru-loader')
        }
    },
    output: {
        path: '/',
        filename: 'testBundle.js'
    },
    alias : {
        'fsevents' : ''
    },
    plugins: [
        new NyanProgressPlugin(),
        new RewirePlugin(),
        new webpack.DefinePlugin({
            __CLIENT__: true,
            __SERVER__: false,
            __PRODUCTION__: JSON.stringify(process.env.NODE_ENV) === 'production',
            __DEV__: JSON.stringify(process.env.NODE_ENV) !== 'production'
        })
    ]
};

var client = {
    name: 'client side webpack',
    target: 'web',
    entry: {
        rehydrate: path.join(__dirname, 'app/rehydrate'),
        app: path.join(__dirname, 'app/app.jsx')
    },
    output: {
        path: path.join(__dirname, 'public/dist'),
        publicPath: nodeCDN,
        filename: '[name].bundle.[hash].js',
        chunkFilename: '[name].chunk.[chunkhash].js'
    },
    resolveLoader: {
        alias: {
            'lift-sass': path.join(__dirname, 'webpack-utils', 'passthru-loader'),
            'react-router-proxy$': 'react-router-proxy-loader'
        }
    },
    module: {
        loaders: [
            {
                test: /\.scss$/,
                loader: ExtractTextPlugin.extract('style-loader', 'css!sass')
            }
            , {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: 'gulp-rev-loader',
                query: manifestParams
            }
        ],
        noParse: [path.join(__dirname, 'app', 'lodash.custom.min.js')]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'commons',
            filename: 'commons.bundle.[hash].js',
            //minChunks: 2,
            chunks: ['rehydrate', 'app']
        }),
        new ExtractTextPlugin('style.[name].[chunkhash].css', {
            disable: false,
            allChunks: true // extract all css from async chunks as well
        }),
        new webpack.DefinePlugin({
            __CLIENT__: true,
            __SERVER__: false,
            __PRODUCTION__: JSON.stringify(process.env.NODE_ENV) === 'production',
            __DEV__: JSON.stringify(process.env.NODE_ENV) !== 'production'
        }),
        new StatsPlugin('webpack-stats.json', {
            assetsByChunkName: false,
            source: false,
            reasons: false,
            modules: false,
            chunks: false
        }),
        new AssetsPlugin({
            filename: 'public/dist/webpack-assets.json',
            prettyPrint: true,
            update: false,
            processOutput: function (assets) {
                return JSON.stringify(Object.assign({assets: assets}, {publicPath: nodeCDN}));
            }
        }),
        new webpack.ProvidePlugin({
            'Promise': 'native-promise-only'
        })
    ],
    resolve: {
        alias: {
            'lodash$' : path.join(__dirname, 'assets', 'scripts', 'lodash.custom.min.js')
        }
    }

};

var server = {
    name: 'server side webpack',
    target: 'node',
    devtool: 'source-map',
    entry: {
        index: path.join(__dirname, 'index.js')
    },
    output: {
        libraryTarget: 'commonjs2',
        path: path.join(__dirname, 'server', 'dist'),
        publicPath: nodeCDN,
        filename: '[name].js'
    },
    resolveLoader: {
        alias: {
            'react-router-proxy$': path.join(__dirname, 'webpack-utils', 'passthru-loader'),
            'lift-sass': path.join(__dirname, 'webpack-utils', 'passthru-loader')
        }
    },
    module: {
        loaders: [
            {
                test: /\.scss$/,
                loader: 'noop-loader'
            }
            , {
                test: /\.(jpe?g|png|gif|svg)$/i,
                loader: 'gulp-rev-loader',
                query: manifestParams
            }
        ]
    },
    plugins: [
        new webpack.DefinePlugin({
            __CLIENT__: false,
            __SERVER__: true,
            __PRODUCTION__: JSON.stringify(process.env.NODE_ENV) === 'production',
            __DEV__: JSON.stringify(process.env.NODE_ENV) !== 'production'
        }),
        new webpack.BannerPlugin('require("source-map-support").install();',
            { raw: true, entryOnly: false })
    ],
    externals: [{ 'react' : true, 'newrelic' : true }, node_externals, config_externals]
};

var integration_client = {
    devtool: false,
    plugins: productionPlugins,
    bail: true,
    debug: false
};

var integration_server = {
    devtool: false,
    plugins: productionPlugins,
    resolveLoader: {
        alias: {
            'lift-sass': path.join(__dirname, 'webpack-utils', 'passthru-loader')
        }
    },
    bail: true,
    cache: false,
    debug: false
};

var production_client = {
    output: {
        publicPath : nodeCDN
    },
    devtool: false,
    plugins: productionPlugins,
    bail: true,
    cache: false,
    debug: false,
    module: {
        loaders: productionLoaders
    }
};

var production_server = {
    output: {
        publicPath : nodeCDN
    },
    devtool: false,
    plugins: productionPlugins,
    resolveLoader: {
        alias: {
            'lift-sass': path.join(__dirname, 'webpack-utils', 'passthru-loader')
        }
    },
    bail: true,
    cache: false,
    debug: false,
    module: {
        loaders: productionLoaders
    }
};

var defaults = {
    context: __dirname,
    node: {
        __dirname: true,
        __filename: true,
        fs: 'empty',
        tls: 'empty',
        net: 'empty',
        console: true
    },
    devtool: '#eval-source-map',
    externals: [/^config[a-z\-0-9]+$/],
    resolve: {
        root: path.join(__dirname),
        fallback: path.join(__dirname, 'node_modules'),
        modulesDirectories: ['app', 'images', 'node_modules'],
        extensions: ['', '.json', '.js', '.jsx', '.scss', '.png', '.jpg', '.jpeg', '.gif'],
        alias: {}
    },
    plugins: [
        new Visualizer(),
        new ProgressPlugin({console :  consoleAvailable}),
        new CachePlugin(myCache),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(true),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) || '"development"',
            'process.env.BUILD_NUMBER': JSON.stringify(process.env.BUILD_NUMBER) || '"42"'
        })
    ],
    resolveLoader: {
        root: __dirname,
        fallback: __dirname + '/node_modules',
        alias: {
            'noop-loader': path.join(__dirname,  'webpack-utils', 'noop-loader'),
            'passthru-loader': path.join(__dirname, 'webpack-utils', 'passthru-loader')
        }
    },
    module: {
        // Disable handling of unknown requires and requires with a single expression
        unknownContextRegExp: /$^/,
        exprContextRegExp: /$^/,
        unknownContextCritical: false,
        exprContextCritical: false,
        loaders: [
            {
                test: /\.json$/,
                loaders: ['json-loader']
            }
            , {
                include: [
                    path.resolve(__dirname, 'app'),
                    path.resolve(__dirname, 'server')
                ],
                test: /\.jsx$/,
                loader: 'babel-loader',
                query: {
                    presets: ['es2015', 'stage-0', 'react']
                }
            }
        ],
        noParse: []
    },
    bail: false,
    cache: true,
    debug: true
};

// file and make sure webpack does not try to parse it
deps.forEach(function(dep) {
    var depPath = path.resolve(node_modules_dir, dep);
    defaults.resolve.alias[dep.split(path.sep)[0]] = depPath;
    defaults.module.noParse.push(depPath);
});

module.exports = process.argv.indexOf('--profile') === -1 ? [config(client), config(server)] : config(client);
module.exports.integration = [config(deepmerge(client, integration_client)), config(deepmerge(server, integration_server))];
module.exports.production = [config(deepmerge(client, production_client)), config(deepmerge(server, production_server))];
module.exports.test = test;
chrisbateman commented 8 years ago

@adjavaherian Can get your stats.json output and share that? (I can't execute your webpack config without the whole app, so I'm not sure what's going on).

Dean177 commented 8 years ago

I was receiving a similar error, but was able to work around it by changing: <script>window.nodesData = JSON.parse('{ ...loadsOfJson... }');</script> to <script>window.nodesData = { ...loadsOfJson... }</script> In the generated stats file.

chrisbateman commented 8 years ago

@Dean177 Can you possibly share your stats.json output?

Dean177 commented 8 years ago

Here is the html file output: stats.html.txt

And webpacks stats.json: buildstats.json.txt

The generated json does work if I drop it on: http://chrisbateman.github.io/webpack-visualizer/

But the generated html file throws: Uncaught SyntaxError: Unexpected token

(For some reason github doesn't allow upload of .json files, hence the .txt extension)

adjavaherian commented 8 years ago

Verified that this works now! Thanks.