Beispiel #1
0
function getLoaders () {
  if (getEnv() === 'dev' || getEnv() === 'dev-daily') {
    return [
      {
        test: /\.js$/,
        loader: StringReplacePlugin.replace('', {
          replacements: getReplace()
        }, 'babel!eslint'),
        // loader: 'babel!eslint',
        exclude: /node_modules|build/
      }, {
        test: /\.html$/,
        loader: 'underscore-template-loader'
      }, {
        test: /\.json$/,
        loader: 'json'
      }, {
        test: /\.less$/,
        loader: 'style!css!postcss!less'
      }, {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  }
  return [
    {
      test: /\.js$/,
      loader: StringReplacePlugin.replace('', {
        replacements: getReplace()
      }, 'babel!eslint'),
      exclude: /node_modules|build/
    }, {
      test: /\.html$/,
      loader: 'underscore-template-loader'
    }, {
      test: /\.json$/,
      loader: 'json'
    }, {
      test: /\.less$/,
      loader: ExtractTextPlugin.extract('style', 'css!postcss!less')
    }, {
      test: /\.(png|jpg|gif|svg)$/,
      loader: 'url',
      query: {
        limit: 10000,
        name: '[name].[ext]?[hash]'
      }
    }
  ]
}
Beispiel #2
0
function createReplacements(substitutions) {
  const replacements = Object.keys(substitutions).map(key => {
    return {
      pattern: new RegExp(`import (.*) from "${escapeRegExp(key)}";`, "gi"),
      replacement: (match, p1) => `import Cldr_${p1} from "${substitutions[key]}"; const ${p1} = Cldr_${p1}._${p1};`
    };
  });

  return StringReplacePlugin.replace({ replacements });
}
    }
};

let config = {
    dev: commonTasks.webpackDevConfig({
        resolve,
        loaders: [ babelLoader ],
        entries: 'examples/*.jsx'
    }), // dev
}; // module.exports

// insert string replace before style loader
// tightly coupled to the order in commonTasks.webpackThemeConfig
const loaders = config.dev.module.loaders;
config.dev.plugins.push( new StringReplacePlugin() );
loaders[loaders.length-3].loaders.splice(1, 0,
    StringReplacePlugin.replace({
        replacements: [
            // replace pseudo classes with class names to show them in static page
            {
                pattern: /:(hover|focus|active)/ig,
                replacement: function (_, state) {
                    return '.__pseudo-' + state;
                }
            }
        ]
    })
);

module.exports = config
Beispiel #4
0
   publicPath: '/',
   filename: 'bundle.js'
 },
 module: {
   loaders: [
     { loader: 'babel', exclude: /node_modules/ },
     { test: /\.css$/, loader: "style!css" }, // "style-loader!css-loader?importLoaders=1"
     { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader:  'url-loader' }, //'url-loader?limit=100000'
     { test: /\.scss$/, loaders: ["style", "css", "sass"]},
     {test: /\.json$/, loader: 'json'},
     {
       exclude: /node_modules/,
       loader: StringReplacePlugin.replace({
         replacements: [{
           // replace server url based on release (ie, localhost:3000 or cctaxonomy.herokuapp.com)
           pattern: /<nconf:server>/g,
           replacement: (match, p1, offset, string) => nconf.get('server:' + (PROD ? 'production' : 'development'))
         }]
       })
     }
   ],
 },
 resolve: {
   extensions: ['', '.js', '.jsx']
 },
 plugins: [
   // Replace <nconf:*>
   new StringReplacePlugin(),
 ].concat(PROD ? [
   new webpack.optimize.UglifyJsPlugin({
     minimize: true,
    filename: 'bundle.js'
  },
  module: {
    loaders: [ {
        test: /\.jade$/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: /@assets_baseurl/ig,
              replacement: function (match, p1, offset, string) {
                var location = 'http://localhost:3000';

                if ((process.env.NODE_ENV || 'development') !== 'development') {
                  location = 'https://cdn.auth0.com/extensions/' + pkg.name + '/assets';
                }

                return location;
              }.bind(this)
            },
            {
              pattern: /@extension_name/ig,
              replacement: function (match, p1, offset, string) {
                return pkg.name+'-'+pkg.version;
              }.bind(this)
            }
          ]
        })
      },
      { test: /\.jade$/, loader: require.resolve('jade-loader') },
      {
        test: /\.json?$/,
        loader: 'json'
config.output.path=path.resolve(__dirname, '../dist/production');
config.output.filename ='[name].[chunkhash].js',
config.output.chunkFilename ="[name].[chunkhash].js"

//打包api 替换
config.module.loaders=(config.module.loaders || []).concat([
  { 
    test: path.resolve(__dirname, '../src' + projectName + 'assets/common/js/config.js'),
    loader: StringReplacePlugin.replace({
      replacements: [
          {
              pattern: /127.0.0.1:8080/,
              replacement: function (match, p1, offset) {
                  return '192.168.1.10';
              }
          },
          {
              pattern: /test.cs0526.allpyra.com/,
              replacement: function (match, p1, offset) {
                  return 'www.seosiwei.com';
              }
          }
      ]})
  }
])

config.plugins = (config.plugins || []).concat([
  //string替换
  new StringReplacePlugin(),
  // this allows uglify to strip all warnings
  // from Vue.js source code.
Beispiel #7
0
            minChunks: 2
        })
    ],

    module: {
        rules: [
            {
                test: namespacedRequireFiles,
                loader: StringReplace.replace(
                    ['babel-loader'],
                    {
                        replacements: [
                            {
                                pattern: /\(function ?\(define\) ?\{/,
                                replacement: function() { return ''; }
                            },
                            {
                                pattern: /\}\)\.call\(this, define \|\| RequireJS\.define\);/,
                                replacement: function() { return ''; }
                            }
                        ]
                    }
                )
            },
            {
                test: /\.(js|jsx)$/,
                exclude: [
                    /node_modules/,
                    namespacedRequireFiles
                ],
                use: 'babel-loader'
             test: path.join(__dirname, 'src'),
             exclude: /tablefilter\/node_modules/,
             options: {
                 compact: false,
                 presets: ['@babel/env']
             },
             loader: 'babel-loader'
         }, {
             test: path.join(__dirname, 'src'),
             loader: StringReplacePlugin.replace({
                 replacements: [{
                     pattern: /{VERSION}/ig,
                     replacement: function (/*match, p1, offset, string*/) {
                         return pkg.version;
                     }
                 },{
                     pattern: /{AUTHOR}/ig,
                     replacement: function () {
                         return pkg.author.name;
                     }
                 }]
             })
         }
     ]
 },
 devtool: 'source-map',
 optimization: {
     minimizer: [
         new UglifyJsPlugin({
             sourceMap: true,
             uglifyOptions: {
        loader: 'file-loader?name=fonts/[name].[ext]'
    },{
        test: /AppConfig.js$/,
        loader: StringReplacePlugin.replace( {
            replacements: [
                {
                    pattern: /<!-- @firebase (\w*?) -->/ig,
                    replacement: function ( match, p1, offset, string ) {
                        return pkg.config.firebase[p1];
                    }
                },{
                    pattern: /<!-- @gmaps (\w*?) -->/ig,
                    replacement: function ( match, p1, offset, string ) {
                        return pkg.config.google.maps[p1];
                    }
                },{
                    pattern: /<!-- @clientId (\w*?) -->/ig,
                    replacement: function ( match, p1, offset, string ) {
                        return pkg.config.google.clientId[p1];
                    }
                },{
                    pattern: /<!-- @authProxy (\w*?) -->/ig,
                    replacement: function ( match, p1, offset, string ) {
                        return pkg.config.authProxy[p1];
                    }
                }
            ]
        } )
    }
];
Beispiel #10
0
   include: /(src)/,
   loader: 'analyticsLoader'
 },
 {
   test: /adaptermanager.js/,
   include: /(src)/,
   loader: 'adapterLoader'
 },
 {
   test: /constants.json$/,
   include: /(src)/,
   loader: StringReplacePlugin.replace({
     replacements: [
       {
         pattern: /%%REPO_AND_VERSION%%/g,
         replacement: function (match, p1, offset, string) {
           return `${prebid.repository.url.split('/')[3]}_prebid_${prebid.version}`;
         }
       }
     ]
   })
 },
   {
     test: /\.js$/,
     include: /(src|test|integrationExamples)/,
     loader: StringReplacePlugin.replace({
       replacements: [
         {
           pattern: /\$\$PREBID_GLOBAL\$\$/g,
           replacement: function (match, p1, offset, string) {
               return prebid.globalVarName;
           }
		loaders: [
			{
                test: configFile.lib_riot_opt_types_mixin_regex,
                loader: stringReplacePlugin.replace({
                    /*
                    *  These replacements tell test coverage reports to ignore code that has been compiled & added
                    *  via webpack, babel, etc
                    */
                    replacements: [
                        {
                            pattern: /else if\(typeof define/g,
                            replacement: function() {
                                return `/* istanbul ignore next */ else if(typeof define`;
                            }
                        },
                        {
                            pattern: /return installedModules/g,
                            replacement: function() {
                                return `/* istanbul ignore next */ return installedModules`;
                            }
                        },
                        {
                            pattern: /function _interopRequireDefault/g,
                            replacement: function() {
                                return `/* istanbul ignore next */ function _interopRequireDefault`;
                            }
                        }
                    ]
                })
            }
		],
        // this is necessary or else test report will be for entire webpack bundle instead of each component
Beispiel #12
0
			]
		}
	};

if(env === 'dist') {
	config.plugins = [];

	config.plugins.push(new StringReplacePlugin());
	config.module.loaders.push({
		test: /\.js?$/,
		exclude: /(node_modules)/,
		loader: StringReplacePlugin.replace({
			replacements: [
				{
					pattern: /Logger\.log\({(.*?)}\);/ig,
					replacement: function(match, p1, offset, string) {
						return '';
					}
				}
			]
		})
	});

	config.plugins.push(
		new webpack.optimize.UglifyJsPlugin({
			compressor: {
				pure_getters: true,
				unsafe: true,
				unsafe_comps: true,
				screw_ie8: true,
				warnings: false
			}
  },

  module: {
    preLoaders: [
      // Replace HTML comments
      {
        test: /\.html$/,
        exclude: /node_modules/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: /<!--\[if\sBOOTSTRAP-HTML\]><!\[endif\]-->/g,
              replacement() {
                return (
                  '<div class="application-loading-indicator ' +
                  'vertical-center">' +
                  bootstrap.HTML +
                  "</div>"
                );
              }
            }
          ]
        })
      },
      {
        test: /\.js$/,
        loader: "source-map-loader",
        exclude: /node_modules/
      }
    ],
    loaders: [
Beispiel #14
0
function compileVarsReplaceLoader () {
  return StringReplacePlugin.replace({
    replacements: [compileVarsReplacement()],
  })
}
Beispiel #15
0
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            'window.jquery': 'jquery'
        }),
        new webpack.optimize.CommonsChunkPlugin('vendor', 'dev/vendor.bundle.js')
    ],
    module: {
        loaders: loaders.concat([
            {
                test: /configuration.ts$/,
                loader: StringReplacePlugin.replace({
                    replacements: [
                        {
                            pattern: '%API_KEY%',
                            replacement: function () {
                                return API_KEY
                            }
                        },
                        {
                            pattern: '%BACKEND_ENV%',
                            replacement: function () {
                                return BACKEND_ENV
                            }
                        }
                    ]
                })
            }
        ])
    }
};
module.exports = (options) => {
    const DATAS = {
        VERSION: `'${utils.parseVersion()}'`,
        DEBUG_INFO_ENABLED: options.env === 'development',
        // The root URL for API calls, ending with a '/' - for example: `"http://www.jhipster.tech:8081/myservice/"`.
        // If this URL is left empty (""), then it will be relative to the current context.
        // If you use an API server, in `prod` mode, you will need to enable CORS
        // (see the `jhipster.cors` common JHipster property in the `application-*.yml` configurations)
        SERVER_API_URL: `""`
    };
    return {
        resolve: {
            extensions: ['.ts', '.js'],
            modules: ['node_modules']
        },
        stats: {
            children: false
        },
        module: {
            rules: [
                { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports-loader?jQuery=jquery' },
                {
                    test: /\.html$/,
                    loader: 'html-loader',
                    options: {
                        minimize: true,
                        caseSensitive: true,
                        removeAttributeQuotes:false,
                        minifyJS:false,
                        minifyCSS:false
                    },
                    exclude: ['./src/main/webapp/index.html']
                },
                {
                    test: /\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/i,
                    loaders: ['file-loader?hash=sha512&digest=hex&name=content/[hash].[ext]']
                },
                {
                    test: /manifest.webapp$/,
                    loader: 'file-loader?name=manifest.webapp!web-app-manifest-loader'
                },
                {
                    test: /app.constants.ts$/,
                    loader: StringReplacePlugin.replace({
                        replacements: [{
                            pattern: /\/\* @toreplace (\w*?) \*\//ig,
                            replacement: (match, p1, offset, string) => `_${p1} = ${DATAS[p1]};`
                        }]
                    })
                }
            ]
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env': {
                    'NODE_ENV': JSON.stringify(options.env)
                }
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'polyfills',
                chunks: ['polyfills']
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                chunks: ['main'],
                minChunks: module => utils.isExternalLib(module)
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: ['polyfills', 'vendor'].reverse()
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: ['manifest'],
                minChunks: Infinity,
            }),
            /**
             * See: https://github.com/angular/angular/issues/11580
             */
            new webpack.ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)@angular/,
                utils.root('src/main/webapp/app'), {}
            ),
            new CopyWebpackPlugin([
                { from: './node_modules/swagger-ui/dist/css', to: 'swagger-ui/dist/css' },
                { from: './node_modules/swagger-ui/dist/lib', to: 'swagger-ui/dist/lib' },
                { from: './node_modules/swagger-ui/dist/swagger-ui.min.js', to: 'swagger-ui/dist/swagger-ui.min.js' },
                { from: './src/main/webapp/swagger-ui/', to: 'swagger-ui' },
                { from: './src/main/webapp/favicon.ico', to: 'favicon.ico' },
                { from: './src/main/webapp/manifest.webapp', to: 'manifest.webapp' },
                // { from: './src/main/webapp/sw.js', to: 'sw.js' },
                // jhipster-needle-add-assets-to-webpack - JHipster will add/remove third-party resources in this array
                { from: './src/main/webapp/robots.txt', to: 'robots.txt' }
            ]),
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            }),
            new HtmlWebpackPlugin({
                template: './src/main/webapp/index.html',
                chunksSortMode: 'dependency',
                inject: 'body'
            }),
            new StringReplacePlugin()
        ]
    };
};
Beispiel #17
0
module.exports = function(grunt) {
    require('time-grunt')(grunt);
    require('load-grunt-tasks')(grunt);
    grunt.loadTasks('grunt/tasks');

    const webpack = require('webpack');
    const pkg = require('./package.json');
    const dt = new Date().toISOString().replace(/T.*/, '');
    const minElectronVersionForUpdate = '1.0.1';
    let zipCommentPlaceholder = 'zip_comment_placeholder_that_will_be_replaced_with_hash';
    const electronVersion = pkg.devDependencies['electron'].replace(/^\D/, '');

    while (zipCommentPlaceholder.length < 512) {
        zipCommentPlaceholder += '.';
    }

    function replaceFont(css) {
        css.walkAtRules('font-face', rule => {
            const fontFamily = rule.nodes.filter(n => n.prop === 'font-family')[0];
            if (!fontFamily) {
                throw 'Bad font rule: ' + rule.toString();
            }
            const value = fontFamily.value.replace(/["']/g, '');
            const fontFiles = {
                FontAwesome: 'fontawesome-webfont.woff'
            };
            const fontFile = fontFiles[value];
            if (!fontFile) {
                throw 'Unsupported font ' + value + ': ' + rule.toString();
            }
            const data = fs.readFileSync('tmp/fonts/' + fontFile, 'base64');
            const src = 'url(data:application/font-woff;charset=utf-8;base64,{data}) format(\'woff\')'
                .replace('{data}', data);
            // var src = 'url(\'../fonts/fontawesome-webfont.woff\') format(\'woff\')';
            rule.nodes = rule.nodes.filter(n => n.prop !== 'src');
            rule.append({ prop: 'src', value: src });
        });
    }

    const webpackConfig = {
        entry: {
            app: 'app',
            vendor: ['jquery', 'underscore', 'backbone', 'kdbxweb', 'baron', 'dropbox', 'pikaday', 'filesaver', 'qrcode',
                'argon2-asm', 'argon2-wasm', 'argon2']
        },
        output: {
            path: path.resolve('.', 'tmp/js'),
            filename: 'app.js'
        },
        stats: {
            colors: false,
            modules: true,
            reasons: true
        },
        progress: false,
        failOnError: true,
        resolve: {
            modules: [path.join(__dirname, 'app/scripts'), path.join(__dirname, 'bower_components')],
            alias: {
                backbone: 'backbone/backbone-min.js',
                underscore: 'underscore/underscore-min.js',
                _: 'underscore/underscore-min.js',
                jquery: 'jquery/dist/jquery.min.js',
                hbs: path.resolve(__dirname, 'node_modules', 'handlebars/runtime.js'),
                kdbxweb: 'kdbxweb/dist/kdbxweb.js',
                dropbox: 'dropbox/lib/dropbox.min.js',
                baron: 'baron/baron.min.js',
                pikaday: 'pikaday/pikaday.js',
                filesaver: 'FileSaver.js/FileSaver.min.js',
                qrcode: 'jsqrcode/dist/qrcode.min.js',
                'argon2-asm': 'argon2-browser/docs/dist/argon2-asm.min.js',
                'argon2-wasm': 'argon2-browser/docs/dist/argon2.wasm',
                'argon2': 'argon2-browser/docs/dist/argon2.min.js',
                templates: path.join(__dirname, 'app/templates')
            }
        },
        module: {
            loaders: [
                { test: /\.hbs$/, loader: StringReplacePlugin.replace('handlebars-loader', { replacements: [{
                    pattern: /\r?\n\s*/g,
                    replacement: function() { return '\n'; }
                }]})},
                { test: /runtime-info\.js$/, loader: StringReplacePlugin.replace({ replacements: [
                    { pattern: /@@VERSION/g, replacement: function() { return pkg.version; } },
                    { pattern: /@@DATE/g, replacement: function() { return dt; } },
                    { pattern: /@@COMMIT/g, replacement: function() { return grunt.config.get('gitinfo.local.branch.current.shortSHA'); } }
                ]})},
                { test: /baron(\.min)?\.js$/, loader: 'exports-loader?baron; delete window.baron;' },
                { test: /pikaday\.js$/, loader: 'uglify-loader' },
                { test: /handlebars/, loader: 'strip-sourcemap-loader' },
                { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader',
                    query: { presets: ['es2015'], cacheDirectory: true }
                },
                { test: /\.json$/, loader: 'json-loader' },
                { test: /argon2-asm\.min\.js$/, loader: 'raw-loader' },
                { test: /argon2\.wasm$/, loader: 'base64-loader' },
                { test: /argon2\.min\.js/, loader: 'raw-loader' } // exports-loader?Module
            ]
        },
        plugins: [
            new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity, filename: 'vendor.js' }),
            new webpack.BannerPlugin('keeweb v' + pkg.version + ', (c) ' + new Date().getFullYear() + ' ' + pkg.author.name +
                ', opensource.org/licenses/' + pkg.license),
            new webpack.ProvidePlugin({ _: 'underscore', $: 'jquery' }),
            new webpack.IgnorePlugin(/^(moment)$/),
            new StringReplacePlugin(),
            new StatsPlugin('stats.json', { chunkModules: true })
        ],
        node: {
            console: false,
            process: false,
            crypto: false,
            Buffer: false,
            __filename: false,
            __dirname: false,
            fs: false,
            setImmediate: false,
            path: false
        },
        externals: {
            xmldom: 'null',
            crypto: 'null',
            fs: 'null',
            path: 'null'
        }
    };

    grunt.initConfig({
        gitinfo: {
            branch: {
                current: {
                    SHA: 'Current HEAD SHA',
                    shortSHA: 'Current HEAD short SHA',
                    name: 'Current branch name',
                    lastCommitTime: 'Last commit time'
                }
            }
        },
        'bower-install-simple': {
            install: {
            }
        },
        clean: {
            dist: ['dist', 'tmp'],
            desktop: ['tmp/desktop', 'dist/desktop']
        },
        copy: {
            html: {
                src: 'app/index.html',
                dest: 'tmp/index.html',
                nonull: true
            },
            favicon: {
                src: 'app/favicon.png',
                dest: 'tmp/favicon.png',
                nonull: true
            },
            touchicon: {
                src: 'app/touchicon.png',
                dest: 'tmp/touchicon.png',
                nonull: true
            },
            fonts: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.*',
                dest: 'tmp/fonts/',
                nonull: true,
                expand: true,
                flatten: true
            },
            'desktop-app-content': {
                cwd: 'desktop/',
                src: '**',
                dest: 'tmp/desktop/app/',
                expand: true,
                nonull: true
            },
            'desktop-windows-helper-ia32': {
                src: 'helper/win32/KeeWebHelper.exe',
                dest: 'tmp/desktop/KeeWeb-win32-ia32/resources/app/',
                nonull: true
            },
            'desktop-windows-helper-x64': {
                src: 'helper/win32/KeeWebHelper.exe',
                dest: 'tmp/desktop/KeeWeb-win32-x64/resources/app/',
                nonull: true
            },
            'desktop-darwin-helper-x64': {
                src: 'helper/darwin/KeeWebHelper',
                dest: 'tmp/desktop/KeeWeb-darwin-x64/KeeWeb.app/Contents/Resources/app/',
                nonull: true,
                options: { mode: '0755' }
            },
            'desktop-win32-dist-x64': {
                src: 'tmp/desktop/KeeWeb.win.x64.exe',
                dest: `dist/desktop/KeeWeb-${pkg.version}.win.x64.exe`,
                nonull: true
            },
            'desktop-win32-dist-ia32': {
                src: 'tmp/desktop/KeeWeb.win.ia32.exe',
                dest: `dist/desktop/KeeWeb-${pkg.version}.win.ia32.exe`,
                nonull: true
            }
        },
        eslint: {
            app: ['app/scripts/**/*.js'],
            desktop: ['desktop/**/*.js', '!desktop/node_modules/**'],
            grunt: ['Gruntfile.js', 'grunt/**/*.js']
        },
        sass: {
            options: {
                sourceMap: false,
                includePaths: ['./bower_components']
            },
            dist: {
                files: {
                    'tmp/css/main.css': 'app/styles/main.scss'
                }
            }
        },
        postcss: {
            options: {
                processors: [
                    replaceFont,
                    require('cssnano')({discardComments: {removeAll: true}})
                ]
            },
            dist: {
                src: 'tmp/css/main.css',
                dest: 'tmp/css/main.css'
            }
        },
        inline: {
            app: {
                src: 'tmp/index.html',
                dest: 'tmp/app.html'
            }
        },
        htmlmin: {
            options: {
                removeComments: true,
                collapseWhitespace: true
            },
            app: {
                files: {
                    'dist/index.html': 'tmp/app.html'
                }
            }
        },
        'string-replace': {
            manifest: {
                options: {
                    replacements: [
                        { pattern: '# YYYY-MM-DD:v0.0.0', replacement: '# ' + dt + ':v' + pkg.version },
                        { pattern: '# updmin:v0.0.0', replacement: '# updmin:v' + minElectronVersionForUpdate }
                    ]
                },
                files: { 'dist/manifest.appcache': 'app/manifest.appcache' }
            },
            'manifest-html': {
                options: { replacements: [{ pattern: '<html', replacement: '<html manifest="manifest.appcache"' }] },
                files: { 'dist/index.html': 'dist/index.html' }
            },
            'desktop-html': {
                options: { replacements: [{ pattern: ' manifest="manifest.appcache"', replacement: '' }] },
                files: { 'tmp/desktop/app/index.html': 'dist/index.html' }
            }
        },
        webpack: {
            js: webpackConfig
        },
        'webpack-dev-server': {
            options: {
                webpack: webpackConfig,
                publicPath: '/tmp/js',
                progress: false
            },
            js: {
                keepalive: true,
                webpack: {
                    devtool: 'source-map'
                },
                port: 8085
            }
        },
        uglify: {
            options: {
                preserveComments: false
            },
            app: {
                files: { 'tmp/js/app.js': ['tmp/js/app.js'] }
            },
            vendor: {
                options: {
                    mangle: false,
                    compress: false
                },
                files: { 'tmp/js/vendor.js': ['tmp/js/vendor.js'] }
            }
        },
        watch: {
            options: {
                interrupt: true,
                debounceDelay: 500
            },
            styles: {
                files: 'app/styles/**/*.scss',
                tasks: ['sass']
            },
            indexhtml: {
                files: 'app/index.html',
                tasks: ['copy:html']
            }
        },
        electron: {
            options: {
                name: 'KeeWeb',
                dir: 'tmp/desktop/app',
                out: 'tmp/desktop',
                electronVersion: electronVersion,
                overwrite: true,
                'app-copyright': 'Copyright © 2016 Antelle',
                'app-version': pkg.version,
                'build-version': '<%= gitinfo.local.branch.current.shortSHA %>'
            },
            linux: {
                options: {
                    platform: 'linux',
                    arch: ['x64', 'ia32'],
                    icon: 'graphics/icon.ico'
                }
            },
            darwin: {
                options: {
                    platform: 'darwin',
                    arch: ['x64'],
                    icon: 'graphics/icon.icns',
                    'app-bundle-id': 'net.antelle.keeweb',
                    'app-category-type': 'public.app-category.productivity',
                    'extend-info': 'package/osx/extend.plist'
                }
            },
            win32: {
                options: {
                    platform: 'win32',
                    arch: ['ia32', 'x64'],
                    icon: 'graphics/icon.ico',
                    'build-version': pkg.version,
                    'version-string': {
                        'CompanyName': 'KeeWeb',
                        'FileDescription': pkg.description,
                        'OriginalFilename': 'KeeWeb.exe',
                        'ProductName': 'KeeWeb',
                        'InternalName': 'KeeWeb'
                    }
                }
            }
        },
        compress: {
            options: {
                level: 6
            },
            'desktop-update': {
                options: { archive: 'dist/desktop/UpdateDesktop.zip', comment: zipCommentPlaceholder },
                files: [
                    { cwd: 'tmp/desktop/app', src: '**', expand: true, nonull: true },
                    { src: 'helper', nonull: true },
                    { src: 'helper/darwin', nonull: true },
                    { src: 'helper/darwin/KeeWebHelper', nonull: true },
                    { src: 'helper/win32', nonull: true },
                    { src: 'helper/win32/KeeWebHelper.exe', nonull: true }
                ]
            },
            'win32-x64': {
                options: { archive: `dist/desktop/KeeWeb-${pkg.version}.win.x64.zip` },
                files: [{ cwd: 'tmp/desktop/KeeWeb-win32-x64', src: '**', expand: true }]
            },
            'win32-ia32': {
                options: { archive: `dist/desktop/KeeWeb-${pkg.version}.win.ia32.zip` },
                files: [{ cwd: 'tmp/desktop/KeeWeb-win32-ia32', src: '**', expand: true }]
            },
            'linux-x64': {
                options: { archive: `dist/desktop/KeeWeb-${pkg.version}.linux.x64.zip` },
                files: [{ cwd: 'tmp/desktop/KeeWeb-linux-x64', src: '**', expand: true }]
            },
            'linux-ia32': {
                options: { archive: `dist/desktop/KeeWeb-${pkg.version}.linux.ia32.zip` },
                files: [{ cwd: 'tmp/desktop/KeeWeb-linux-ia32', src: '**', expand: true }]
            }
        },
        appdmg: {
            options: {
                title: 'KeeWeb',
                icon: 'graphics/icon.icns',
                background: 'graphics/background.png',
                'background-color': '#E0E6F9',
                'icon-size': 80,
                window: { size: { width: 658, height: 498 } },
                contents: [
                    { x: 438, y: 344, type: 'link', path: '/Applications' },
                    { x: 192, y: 344, type: 'file', path: 'tmp/desktop/KeeWeb-darwin-x64/KeeWeb.app' }
                ]
            },
            app: {
                dest: `dist/desktop/KeeWeb-${pkg.version}.mac.dmg`
            }
        },
        nsis: {
            options: {
                vars: {
                    version: pkg.version,
                    rev: function() { return grunt.config.get('gitinfo.local.branch.current.shortSHA'); },
                    homepage: pkg.homepage
                }
            },
            'win32-x64': {
                options: {
                    installScript: 'package/nsis/main.nsi',
                    arch: 'x64',
                    output: 'tmp/desktop/KeeWeb.win.x64.exe'
                }
            },
            'win32-un-x64': {
                options: {
                    installScript: 'package/nsis/main-un.nsi',
                    arch: 'x64',
                    output: 'tmp/desktop/KeeWeb-win32-x64/uninst.exe'
                }
            },
            'win32-ia32': {
                options: {
                    installScript: 'package/nsis/main.nsi',
                    arch: 'ia32',
                    output: 'tmp/desktop/KeeWeb.win.ia32.exe'
                }
            },
            'win32-un-ia32': {
                options: {
                    installScript: 'package/nsis/main-un.nsi',
                    arch: 'ia32',
                    output: 'tmp/desktop/KeeWeb-win32-ia32/uninst.exe'
                }
            }
        },
        deb: {
            'linux-x64': {
                options: {
                    tmpPath: 'tmp/desktop/',
                    package: {
                        name: 'keeweb-desktop',
                        version: pkg.version,
                        description: pkg.description,
                        author: pkg.author,
                        homepage: pkg.homepage,
                        rev: function() { return grunt.config.get('gitinfo.local.branch.current.shortSHA'); }
                    },
                    info: {
                        arch: 'amd64',
                        targetDir: 'dist/desktop',
                        pkgName: `KeeWeb-${pkg.version}.linux.x64.deb`,
                        appName: 'KeeWeb',
                        depends: 'libappindicator1',
                        scripts: {
                            postinst: 'package/deb/scripts/postinst'
                        }
                    }
                },
                files: [
                    {
                        cwd: 'package/deb/usr',
                        src: '**',
                        dest: '/usr',
                        expand: true,
                        nonull: true
                    },
                    {
                        cwd: 'tmp/desktop/KeeWeb-linux-x64/',
                        src: '**',
                        dest: '/opt/keeweb-desktop',
                        expand: true,
                        nonull: true
                    },
                    {
                        src: 'graphics/128x128.png',
                        dest: '/usr/share/icons/hicolor/128x128/apps/keeweb.png',
                        nonull: true
                    }]
            }
        },
        'sign-archive': {
            'desktop-update': {
                options: {
                    file: 'dist/desktop/UpdateDesktop.zip',
                    signature: zipCommentPlaceholder,
                    privateKey: 'keys/private-key.pem'
                }
            }
        },
        'validate-desktop-update': {
            desktop: {
                options: {
                    file: 'dist/desktop/UpdateDesktop.zip',
                    expected: [
                        'main.js', 'app.js', 'index.html', 'package.json', 'icon.png',
                        'node_modules/node-stream-zip/node_stream_zip.js',
                        'helper/darwin/KeeWebHelper',
                        'helper/win32/KeeWebHelper.exe'
                    ],
                    expectedCount: 15,
                    publicKey: 'app/resources/public-key.pem'
                }
            }
        },
        'sign-html': {
            'app': {
                options: {
                    file: 'dist/index.html',
                    privateKey: 'keys/private-key.pem'
                }
            }
        },
        'sign-exe': {
            options: {
                spc: 'keys/code-sign-win32.spc',
                pvk: 'keys/code-sign-win32.pvk',
                algo: 'sha1',
                url: pkg.homepage,
                keytarPasswordService: 'code-sign-win32-keeweb',
                keytarPasswordAccount: 'code-sign-win32-keeweb'
            },
            'win32-build-x64': {
                options: {
                    files: {
                        'tmp/desktop/KeeWeb-win32-x64/KeeWeb.exe': 'KeeWeb',
                        'tmp/desktop/KeeWeb-win32-x64/ffmpeg.dll': '',
                        'tmp/desktop/KeeWeb-win32-x64/libEGL.dll': 'ANGLE libEGL Dynamic Link Library',
                        'tmp/desktop/KeeWeb-win32-x64/libGLESv2.dll': 'ANGLE libGLESv2 Dynamic Link Library',
                        'tmp/desktop/KeeWeb-win32-x64/node.dll': 'Node.js'
                    }
                }
            },
            'win32-build-ia32': {
                options: {
                    files: {
                        'tmp/desktop/KeeWeb-win32-ia32/KeeWeb.exe': 'KeeWeb',
                        'tmp/desktop/KeeWeb-win32-ia32/ffmpeg.dll': '',
                        'tmp/desktop/KeeWeb-win32-ia32/libEGL.dll': 'ANGLE libEGL Dynamic Link Library',
                        'tmp/desktop/KeeWeb-win32-ia32/libGLESv2.dll': 'ANGLE libGLESv2 Dynamic Link Library',
                        'tmp/desktop/KeeWeb-win32-ia32/node.dll': 'Node.js'
                    }
                }
            },
            'win32-uninst-x64': {
                options: {
                    files: {
                        'tmp/desktop/KeeWeb-win32-x64/uninst.exe': 'KeeWeb Uninstaller'
                    }
                }
            },
            'win32-uninst-ia32': {
                options: {
                    files: {
                        'tmp/desktop/KeeWeb-win32-ia32/uninst.exe': 'KeeWeb Uninstaller'
                    }
                }
            },
            'win32-installer-x64': {
                options: {
                    files: {
                        'tmp/desktop/KeeWeb.win.x64.exe': 'KeeWeb Setup'
                    }
                }
            },
            'win32-installer-ia32': {
                options: {
                    files: {
                        'tmp/desktop/KeeWeb.win.ia32.exe': 'KeeWeb Setup'
                    }
                }
            }
        },
        'concurrent': {
            options: {
                logConcurrentOutput: true
            },
            'dev-server': [
                'watch:styles',
                'webpack-dev-server'
            ]
        }
    });

    // compound builder tasks

    grunt.registerTask('build-web-app', [
        'gitinfo',
        'bower-install-simple',
        'clean',
        'eslint',
        'copy:html',
        'copy:favicon',
        'copy:touchicon',
        'copy:fonts',
        'webpack',
        'uglify',
        'sass',
        'postcss',
        'inline',
        'htmlmin',
        'string-replace:manifest-html',
        'string-replace:manifest',
        'sign-html'
    ]);

    grunt.registerTask('build-desktop-app-content', [
        'copy:desktop-app-content',
        'string-replace:desktop-html'
    ]);

    grunt.registerTask('build-desktop-update', [
        'compress:desktop-update',
        'sign-archive:desktop-update',
        'validate-desktop-update'
    ]);

    grunt.registerTask('build-desktop-executables', [
        'electron',
        'sign-exe:win32-build-x64',
        'sign-exe:win32-build-ia32',
        'copy:desktop-darwin-helper-x64',
        'copy:desktop-windows-helper-ia32',
        'copy:desktop-windows-helper-x64'
    ]);

    grunt.registerTask('build-desktop-archives', [
        'compress:win32-x64',
        'compress:win32-ia32',
        'compress:linux-x64',
        'compress:linux-ia32'
    ]);

    grunt.registerTask('build-desktop-dist-darwin', [
        'appdmg'
    ]);

    grunt.registerTask('build-desktop-dist-win32', [
        'nsis:win32-un-x64',
        'nsis:win32-un-ia32',
        'sign-exe:win32-uninst-x64',
        'sign-exe:win32-uninst-ia32',
        'nsis:win32-x64',
        'nsis:win32-ia32',
        'sign-exe:win32-installer-x64',
        'sign-exe:win32-installer-ia32',
        'copy:desktop-win32-dist-x64',
        'copy:desktop-win32-dist-ia32'
    ]);

    grunt.registerTask('build-desktop-dist-linux', [
        'deb:linux-x64'
    ]);

    grunt.registerTask('build-desktop-dist', [
        'build-desktop-dist-darwin',
        'build-desktop-dist-win32',
        'build-desktop-dist-linux'
    ]);

    grunt.registerTask('build-desktop', [
        'gitinfo',
        'clean:desktop',
        'build-desktop-app-content',
        'build-desktop-update',
        'build-desktop-executables',
        'build-desktop-archives',
        'build-desktop-dist'
    ]);

    // entry point tasks

    grunt.registerTask('default', 'Default: build web app', [
        'build-web-app'
    ]);

    grunt.registerTask('dev', 'Build project and start web server and watcher', [
        'build-web-app',
        'devsrv'
    ]);

    grunt.registerTask('devsrv', 'Start web server and watcher', [
        'concurrent:dev-server'
    ]);

    grunt.registerTask('desktop', 'Build web and desktop apps for all platforms', [
        'default',
        'build-desktop'
    ]);
};
module.exports = (options) => {
    const DATAS = {
        VERSION: `'${utils.parseVersion()}'`,
        DEBUG_INFO_ENABLED: options.env === 'development'
    };
    return {
        resolve: {
            extensions: ['.ts', '.js'],
            modules: ['node_modules']
        },
        stats: {
            children: false
        },
        module: {
            rules: [
                { test: /bootstrap\/dist\/js\/umd\//, loader: 'imports-loader?jQuery=jquery' },
                {
                    test: /\.html$/,
                    loader: 'html-loader',
                    options: {
                        minimize: true,
                        caseSensitive: true,
                        removeAttributeQuotes:false,
                        minifyJS:false,
                        minifyCSS:false
                    },
                    exclude: ['./src/main/webapp/index.html']
                },
                {
                    test: /\.(jpe?g|png|gif|svg|woff2?|ttf|eot)$/i,
                    loaders: ['file-loader?hash=sha512&digest=hex&name=content/[hash].[ext]']
                },
                {
                    test: /manifest.webapp$/,
                    loader: 'file-loader?name=manifest.webapp!web-app-manifest-loader'
                },
                {
                    test: /app.constants.ts$/,
                    loader: StringReplacePlugin.replace({
                        replacements: [{
                            pattern: /\/\* @toreplace (\w*?) \*\//ig,
                            replacement: (match, p1, offset, string) => `_${p1} = ${DATAS[p1]};`
                        }]
                    })
                }
            ]
        },
        plugins: [
            new webpack.DefinePlugin({
                'process.env': {
                    'NODE_ENV': JSON.stringify(options.env)
                }
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'polyfills',
                chunks: ['polyfills']
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                chunks: ['main'],
                minChunks: module => utils.isExternalLib(module)
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: ['polyfills', 'vendor'].reverse()
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: ['manifest'],
                minChunks: Infinity,
            }),
            /**
             * See: https://github.com/angular/angular/issues/11580
             */
            new webpack.ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)@angular/,
                utils.root('src/main/webapp/app'), {}
            ),
            new CopyWebpackPlugin([
                { from: './node_modules/core-js/client/shim.min.js', to: 'core-js-shim.min.js' },
                { from: './node_modules/swagger-ui/dist/css', to: 'swagger-ui/dist/css' },
                { from: './node_modules/swagger-ui/dist/lib', to: 'swagger-ui/dist/lib' },
                { from: './node_modules/swagger-ui/dist/swagger-ui.min.js', to: 'swagger-ui/dist/swagger-ui.min.js' },
                { from: './src/main/webapp/swagger-ui/', to: 'swagger-ui' },
                { from: './src/main/webapp/favicon.ico', to: 'favicon.ico' },
                { from: './src/main/webapp/manifest.webapp', to: 'manifest.webapp' },
                // { from: './src/main/webapp/sw.js', to: 'sw.js' },
                { from: './src/main/webapp/robots.txt', to: 'robots.txt' }
            ]),
            new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            }),
            new MergeJsonWebpackPlugin({
                output: {
                    groupBy: [
                        { pattern: "./src/main/webapp/i18n/en/*.json", fileName: "./i18n/en.json" }
                        // jhipster-needle-i18n-language-webpack - JHipster will add/remove languages in this array
                    ]
                }
            }),
            new HtmlWebpackPlugin({
                template: './src/main/webapp/index.html',
                chunksSortMode: 'dependency',
                inject: 'body'
            }),
            new StringReplacePlugin()
        ]
    };
};
      },
      {
        test: /\.gif$/,
        loader: addImageOptimizer(
          "file?name=./[hash]-[name].[ext]&limit=100000&mimetype=image/gif"
        )
      },
      {
        test: /\.jpg$/,
        loader: addImageOptimizer("file?name=./[hash]-[name].[ext]")
      },
      // Replace @@variables
      {
        test: /.js$/,
        exclude: /node_modules/,
        loader: StringReplacePlugin.replace({
          replacements: [
            {
              pattern: /@@(\w+)/gi,
              replacement(match, key) {
                return REPLACEMENT_VARS[key];
              }
            }
          ]
        })
      }
    ]),
    postLoaders: webpackConfig.module.postLoaders
  }
});
Beispiel #20
0
		filename: 'pdfmake.js',
		libraryTarget: 'umd'
	},
	resolve: {
		alias: {
			fs: path.join(__dirname, './src/browser-extensions/virtual-fs.js')
		}
	},
	module: {
		rules: [
			{test: /pdfMake.js$/, loader: 'expose-loader?pdfMake', include: [path.join(__dirname, './src/browser-extensions')]},
			{test: /pdfkit[/\\]js[/\\]mixins[/\\]fonts.js$/, loader: StringReplacePlugin.replace({
					replacements: [
						{
							pattern: 'return this.font(\'Helvetica\');',
							replacement: function () {
								return '';
							}
						}
					]})
			},
			{test: /fontkit[/\\]index.js$/, loader: StringReplacePlugin.replace({
					replacements: [
						{
							pattern: /fs\./g,
							replacement: function () {
								return 'require(\'fs\').';
							}
						}
					]})
			},
Beispiel #21
0
module.exports = function(grunt) {
    require('time-grunt')(grunt);
    require('load-grunt-tasks')(grunt);
    grunt.loadTasks('grunt/tasks');

    var webpack = require('webpack');
    var pkg = require('./package.json');
    var dt = new Date().toISOString().replace(/T.*/, '');
    var minElectronVersionForUpdate = '1.0.1';
    var zipCommentPlaceholder = 'zip_comment_placeholder_that_will_be_replaced_with_hash';
    var electronVersion = pkg.devDependencies['electron-prebuilt'].replace(/^\D/, '');

    while (zipCommentPlaceholder.length < 512) {
        zipCommentPlaceholder += '.';
    }

    function replaceFont(css) {
        css.walkAtRules('font-face', function (rule) {
            var fontFamily = rule.nodes.filter(function(n) { return n.prop === 'font-family'; })[0];
            if (!fontFamily) {
                throw 'Bad font rule: ' + rule.toString();
            }
            var value = fontFamily.value.replace(/["']/g, '');
            var fontFiles = {
                FontAwesome: 'fontawesome-webfont.woff'
            };
            var fontFile = fontFiles[value];
            if (!fontFile) {
                throw 'Unsupported font ' + value + ': ' + rule.toString();
            }
            var data = fs.readFileSync('tmp/fonts/' + fontFile, 'base64');
            var src = 'url(data:application/font-woff;charset=utf-8;base64,{data}) format(\'woff\')'
                .replace('{data}', data);
            //var src = 'url(\'../fonts/fontawesome-webfont.woff\') format(\'woff\')';
            rule.nodes = rule.nodes.filter(function(n) { return n.prop !== 'src'; });
            rule.append({ prop: 'src', value: src });
        });
    }

    grunt.initConfig({
        gitinfo: {
            branch: {
                current: {
                    SHA: 'Current HEAD SHA',
                    shortSHA: 'Current HEAD short SHA',
                    name: 'Current branch name',
                    lastCommitTime: 'Last commit time'
                }
            }
        },
        'bower-install-simple': {
            install: {
            }
        },
        clean: {
            dist: ['dist', 'tmp'],
            'desktop_dist': ['dist/desktop'],
            'desktop_tmp': ['tmp/desktop']
        },
        copy: {
            html: {
                src: 'app/index.html',
                dest: 'tmp/index.html',
                nonull: true
            },
            favicon: {
                src: 'app/favicon.png',
                dest: 'tmp/favicon.png',
                nonull: true
            },
            touchicon: {
                src: 'app/touchicon.png',
                dest: 'tmp/touchicon.png',
                nonull: true
            },
            fonts: {
                src: 'bower_components/font-awesome/fonts/fontawesome-webfont.*',
                dest: 'tmp/fonts/',
                nonull: true,
                expand: true,
                flatten: true
            },
            'desktop_app_content': {
                cwd: 'electron/',
                src: '**',
                dest: 'tmp/desktop/app/',
                expand: true,
                nonull: true
            },
            'desktop_windows_helper': {
                src: 'helper/win32/KeeWebHelper.exe',
                dest: 'tmp/desktop/app/',
                nonull: true
            },
            'desktop_osx': {
                src: 'tmp/desktop/mac/KeeWeb-' + pkg.version + '.dmg',
                dest: 'dist/desktop/KeeWeb.mac.dmg',
                nonull: true
            },
            'desktop_win': {
                src: 'tmp/desktop/win-ia32/KeeWeb Setup ' + pkg.version + '-ia32.exe',
                dest: 'dist/desktop/KeeWeb.win32.exe',
                nonull: true
            },
            'desktop_linux_x64': {
                src: 'tmp/desktop/KeeWeb.linux.x64.zip',
                dest: 'dist/desktop/KeeWeb.linux.x64.zip',
                nonull: true
            },
            'desktop_linux_ia32': {
                src: 'tmp/desktop/KeeWeb.linux.ia32.zip',
                dest: 'dist/desktop/KeeWeb.linux.ia32.zip',
                nonull: true
            },
            'desktop_linux_deb_x64': {
                src: 'tmp/desktop/keeweb-desktop_*_amd64.deb',
                dest: 'dist/desktop/KeeWeb.linux.x64.deb',
                nonull: true
            }
        },
        jshint: {
            options: {
                jshintrc: true
            },
            all: ['app/scripts/**/*.js']
        },
        sass: {
            options: {
                sourceMap: false,
                includePaths: ['./bower_components']
            },
            dist: {
                files: {
                    'tmp/css/main.css': 'app/styles/main.scss'
                }
            }
        },
        postcss: {
            options: {
                processors: [
                    replaceFont,
                    require('cssnano')({discardComments: {removeAll: true}})
                ]
            },
            dist: {
                src: 'tmp/css/main.css',
                dest: 'tmp/css/main.css'
            }
        },
        inline: {
            app: {
                src: 'tmp/index.html',
                dest: 'tmp/app.html'
            }
        },
        htmlmin: {
            options: {
                removeComments: true,
                collapseWhitespace: true
            },
            app: {
                files: {
                    'dist/index.html': 'tmp/app.html'
                }
            }
        },
        'string-replace': {
            manifest: {
                options: {
                    replacements: [
                        { pattern: '# YYYY-MM-DD:v0.0.0', replacement: '# ' + dt + ':v' + pkg.version },
                        { pattern: '# updmin:v0.0.0', replacement: '# updmin:v' + minElectronVersionForUpdate }
                    ]
                },
                files: { 'dist/manifest.appcache': 'app/manifest.appcache' }
            },
            'manifest_html': {
                options: { replacements: [{ pattern: '<html', replacement: '<html manifest="manifest.appcache"' }] },
                files: { 'dist/index.html': 'dist/index.html' }
            },
            'desktop_html': {
                options: { replacements: [{ pattern: ' manifest="manifest.appcache"', replacement: '' }] },
                files: { 'tmp/desktop/app/index.html': 'dist/index.html' }
            }
        },
        webpack: {
            js: {
                entry: {
                    app: 'app',
                    vendor: ['jquery', 'underscore', 'backbone', 'kdbxweb', 'baron', 'dropbox', 'pikaday', 'filesaver', 'qrcode']
                },
                output: {
                    path: 'tmp/js',
                    filename: 'app.js'
                },
                stats: {
                    colors: false,
                    modules: true,
                    reasons: true
                },
                progress: false,
                failOnError: true,
                resolve: {
                    root: [path.join(__dirname, 'app/scripts'), path.join(__dirname, 'bower_components')],
                    alias: {
                        backbone: 'backbone/backbone-min.js',
                        underscore: 'underscore/underscore-min.js',
                        _: 'underscore/underscore-min.js',
                        jquery: 'jquery/dist/jquery.min.js',
                        hbs: 'handlebars/runtime.js',
                        kdbxweb: 'kdbxweb/dist/kdbxweb.js',
                        dropbox: 'dropbox/lib/dropbox.min.js',
                        baron: 'baron/baron.min.js',
                        pikaday: 'pikaday/pikaday.js',
                        filesaver: 'FileSaver.js/FileSaver.min.js',
                        qrcode: 'jsqrcode/dist/qrcode.min.js',
                        templates: path.join(__dirname, 'app/templates')
                    }
                },
                module: {
                    loaders: [
                        { test: /\.hbs$/, loader: StringReplacePlugin.replace('handlebars-loader', { replacements: [{
                            pattern: /\r?\n\s*/g,
                            replacement: function() { return '\n'; }
                        }]})},
                        { test: /runtime\-info\.js$/, loader: StringReplacePlugin.replace({ replacements: [
                            { pattern: /@@VERSION/g, replacement: function() { return pkg.version; } },
                            { pattern: /@@DATE/g, replacement: function() { return dt; } },
                            { pattern: /@@COMMIT/g, replacement: function() { return grunt.config.get('gitinfo.local.branch.current.shortSHA'); } }
                        ]})},
                        { test: /baron(\.min)?\.js$/, loader: 'exports?baron; delete window.baron;' },
                        { test: /pikadat\.js$/, loader: 'uglify' },
                        { test: /handlebars/, loader: 'strip-sourcemap-loader' }
                    ]
                },
                plugins: [
                    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.js'),
                    new webpack.BannerPlugin('keeweb v' + pkg.version + ', (c) 2015 ' + pkg.author.name +
                        ', opensource.org/licenses/' + pkg.license),
                    new webpack.optimize.OccurenceOrderPlugin(),
                    new webpack.ProvidePlugin({ _: 'underscore', $: 'jquery' }),
                    new webpack.IgnorePlugin(/^(moment)$/),
                    new StringReplacePlugin()
                ],
                node: {
                    console: false,
                    process: false,
                    Buffer: false,
                    __filename: false,
                    __dirname: false
                },
                externals: {
                    xmldom: 'null'
                }
            }
        },
        uglify: {
            options: {
                preserveComments: false
            },
            app: {
                files: { 'tmp/js/app.js': ['tmp/js/app.js'] }
            },
            vendor: {
                options: {
                    mangle: false,
                    compress: false
                },
                files: { 'tmp/js/vendor.js': ['tmp/js/vendor.js'] }
            }
        },
        watch: {
            options: {
                interrupt: true,
                debounceDelay: 500
            },
            scripts: {
                files: ['app/scripts/**/*.js', 'app/templates/**/*.hbs'],
                tasks: ['webpack']
            },
            styles: {
                files: 'app/styles/**/*.scss',
                tasks: ['sass']
            },
            indexhtml: {
                files: 'app/index.html',
                tasks: ['copy:html']
            }
        },
        electron: {
            options: {
                name: 'KeeWeb',
                dir: 'tmp/desktop/app',
                out: 'tmp/desktop',
                version: electronVersion,
                overwrite: true,
                'app-version': pkg.version,
                'build-version': '<%= gitinfo.local.branch.current.shortSHA %>'
            },
            linux64: {
                options: {
                    platform: 'linux',
                    arch: 'x64',
                    icon: 'graphics/app.ico'
                }
            },
            linux32: {
                options: {
                    platform: 'linux',
                    arch: 'ia32',
                    icon: 'graphics/app.ico'
                }
            }
        },
        'electron-builder': {
            options: {
                publish: 'never',
                dist: false,
                projectDir: __dirname,
                appDir: 'tmp/desktop/app',
                sign: false
            },
            osx: {
                options: {
                    platforms: ['osx'],
                    arch: 'x64'
                }
            },
            win: {
                options: {
                    platform: ['win32'],
                    arch: 'ia32'
                }
            }
            // linux64: {
            //     options: {
            //         platform: ['linux'],
            //         arch: 'x64'
            //     }
            // },
            // linux32: {
            //     options: {
            //         platform: ['linux'],
            //         arch: 'ia32'
            //     }
            // }
        },
        compress: {
            linux64: {
                options: { archive: 'tmp/desktop/KeeWeb.linux.x64.zip' },
                files: [{ cwd: 'tmp/desktop/KeeWeb-linux-x64', src: '**', expand: true }]
            },
            linux32: {
                options: { archive: 'tmp/desktop/KeeWeb.linux.ia32.zip' },
                files: [{ cwd: 'tmp/desktop/KeeWeb-linux-ia32', src: '**', expand: true }]
            },
            'desktop_update': {
                options: { archive: 'dist/desktop/UpdateDesktop.zip', comment: zipCommentPlaceholder },
                files: [{ cwd: 'tmp/desktop/app', src: '**', expand: true }]
            }
        },
        deb: {
            linux64: {
                options: {
                    tmpPath: 'tmp/desktop/',
                    package: {
                        name: 'keeweb-desktop',
                        version: pkg.version,
                        description: pkg.description,
                        author: pkg.author,
                        homepage: pkg.homepage,
                        rev: function() { return grunt.config.get('gitinfo.local.branch.current.shortSHA'); }
                    },
                    info: {
                        arch: 'amd64',
                        targetDir: 'tmp/desktop',
                        appName: 'KeeWeb',
                        scripts: {
                            postinst: 'package/deb/scripts/postinst'
                        }
                    }
                },
                files: [
                    {
                        cwd: 'package/deb/usr',
                        src: '**',
                        dest: '/usr',
                        expand: true,
                        nonull: true
                    },
                    {
                        cwd: 'tmp/desktop/KeeWeb-linux-x64/',
                        src: '**',
                        dest: '/opt/keeweb-desktop',
                        expand: true,
                        nonull: true
                    },
                    {
                        src: 'graphics/128x128.png',
                        dest: '/usr/share/icons/hicolor/128x128/apps/keeweb.png',
                        nonull: true
                    }]
            }
        },
        'sign-archive': {
            'desktop_update': {
                options: {
                    file: 'dist/desktop/UpdateDesktop.zip',
                    signature: zipCommentPlaceholder,
                    privateKey: 'keys/private-key.pem'
                }
            }
        },
        'validate-desktop-update': {
            desktop: {
                options: {
                    file: 'dist/desktop/UpdateDesktop.zip',
                    expected: ['main.js', 'app.js', 'index.html', 'package.json', 'node_modules/node-stream-zip/node_stream_zip.js'],
                    publicKey: 'app/resources/public-key.pem'
                }
            }
        },
        'sign-html': {
            'app': {
                options: {
                    file: 'dist/index.html',
                    privateKey: 'keys/private-key.pem'
                }
            }
        },
        'sign-exe': {
            'win-installer': {
                options: {
                    file: 'tmp/desktop/win-ia32/KeeWeb Setup ' + pkg.version + '-ia32.exe',
                    spc: 'keys/code-sign-win32.spc',
                    pvk: 'keys/code-sign-win32.pvk',
                    algo: 'sha1',
                    name: 'KeeWeb Setup',
                    url: pkg.homepage
                }
            }
        }
    });

    grunt.registerTask('default', [
        'gitinfo',
        'bower-install-simple',
        'clean',
        'jshint',
        'copy:html',
        'copy:favicon',
        'copy:touchicon',
        'copy:fonts',
        'webpack',
        'uglify',
        'sass',
        'postcss',
        'inline',
        'htmlmin',
        'string-replace:manifest_html',
        'string-replace:manifest',
        'sign-html'
    ]);

    grunt.registerTask('desktop', [
        'default',
        'gitinfo',
        'clean:desktop_tmp',
        'clean:desktop_dist',
        'copy:desktop_app_content',
        'string-replace:desktop_html',
        'compress:desktop_update',
        'sign-archive:desktop_update',
        'validate-desktop-update',
        'electron',
        'electron-builder:osx',
        'copy:desktop_windows_helper',
        'electron-builder:win',
        'compress:linux64',
        'compress:linux32',
        'deb:linux64',
        'sign-exe:win-installer',
        'copy:desktop_osx',
        'copy:desktop_win',
        'copy:desktop_linux_x64',
        'copy:desktop_linux_ia32',
        'copy:desktop_linux_deb_x64',
        'clean:desktop_tmp'
    ]);
};
Beispiel #22
0
  output: {
    path: path.join(__dirname, './build'),
    filename: 'pdfmake.js'
  },
  resolve: {
    alias: {
      fs: path.join(__dirname, './src/browser-extensions/virtual-fs.js')
    }
  },
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json' },
      { test: /pdfMake.js$/, loader: 'expose?pdfMake', include: [ path.join(__dirname, './src/browser-extensions')] },
      { test: /pdfkit[\/\\]js[\/\\]mixins[\/\\]fonts.js$/, loader: StringReplacePlugin.replace({
        replacements: [
          {
            pattern: 'return this.font(\'Helvetica\');',
            replacement: ''
          }
        ]})
      }
    ]
  },
  plugins: [
    new StringReplacePlugin()
  ],
	externals: {
    	'lodash': '_'
	}
};
 loader: StringReplace.replace(
     ['babel-loader'],
     {
         replacements: [
             {
                 pattern: defineHeader,
                 replacement: function() { return ''; }
             },
             {
                 pattern: defineFooter,
                 replacement: function() { return ''; }
             },
             {
                 pattern: /(\/\* RequireJS) \*\//g,
                 replacement: function(match, p1) { return p1; }
             },
             {
                 pattern: /\/\* Webpack/g,
                 replacement: function(match) { return match + ' */'; }
             },
             {
                 pattern: /text!(.*?\.underscore)/g,
                 replacement: function(match, p1) { return p1; }
             },
             {
                 pattern: /RequireJS.require/g,
                 replacement: function() {
                     return 'require';
                 }
             }
         ]
     }
 )
function configureWebpack(terriaJSBasePath, config, devMode, hot, ExtractTextPlugin, disableStyleLoader) {
    const cesiumDir = path.dirname(require.resolve('terriajs-cesium/package.json'));

    config.resolve = config.resolve || {};
    config.resolve.extensions = config.resolve.extensions || ['*', '.webpack.js', '.web.js', '.js'];
    config.resolve.extensions.push('.jsx');
    config.resolve.alias = config.resolve.alias || {};
    config.resolve.modules = config.resolve.modules || [];
    config.resolve.modules.push(path.resolve(terriaJSBasePath, 'wwwroot'));

    config.module = config.module || {};
    config.module.loaders = config.module.loaders || [];

    config.module.loaders.push({
        test: /\.js?$/,
        include: path.dirname(require.resolve('terriajs-cesium')),
        exclude: [
            require.resolve('terriajs-cesium/Source/ThirdParty/zip'),
            require.resolve('terriajs-cesium/Source/Core/buildModuleUrl'),
            require.resolve('terriajs-cesium/Source/Core/TaskProcessor')
        ],
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /buildModuleUrl\([\'|\"](.*)[\'|\"]\)/ig,
                    replacement: function (match, p1, offset, string) {
                        return "require('" + cesiumDir.replace(/\\/g, '\\\\') + "/Source/" + p1.replace(/\\/g, '\\\\') + "')";
                    }
                }
            ]
        })
    });

    // The sprintf module included by Cesium includes a license comment with a big
    // pile of links, some of which are apparently dodgy and cause Websense to flag
    // web workers that include the comment as malicious.  So here we munge URLs in
    // comments so broken security software doesn't consider them links that a user
    // might actually visit.
    config.module.loaders.push({
        test: /\.js?$/,
        include: path.resolve(cesiumDir, 'Source', 'ThirdParty'),
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /\/\*[\S\s]*?\*\//g, // find multi-line comments
                    replacement: function (match) {
                        // replace http:// and https:// with a spelling-out of it.
                        return match.replace(/(https?):\/\//g, '$1-colon-slashslash ');
                    }
                }
            ]
        })
    });
    // Use Babel to compile our JavaScript files.
    config.module.loaders.push({
        test: /\.jsx?$/,
        include: [
            path.resolve(terriaJSBasePath, 'lib'),
            path.resolve(terriaJSBasePath, 'test')
        ],
        loader: 'babel-loader',
        query: {
            sourceMap: false, // generated sourcemaps are currently bad, see https://phabricator.babeljs.io/T7257
            presets: ['es2015', 'react'],
            plugins: [
                'jsx-control-statements'
            ]
        }
    });

    // Use the raw loader for our view HTML.  We don't use the html-loader because it
    // will doing things with images that we don't (currently) want.
    config.module.loaders.push({
        test: /\.html$/,
        include: path.resolve(terriaJSBasePath, 'lib', 'Views'),
        loader: 'raw-loader'
    });

    // Allow XML in the models directory to be required-in as a raw text.
    config.module.loaders.push({
        test: /\.xml$/,
        include: path.resolve(terriaJSBasePath, 'lib', 'Models'),
        loader: 'raw-loader'
    });

    config.module.loaders.push({
        test: /\.json|xml$/,
        include: path.resolve(cesiumDir, 'Source', 'Assets'),
        loader: 'file-loader'
    });

    config.module.loaders.push({
        test: /\.js$/,
        include: path.resolve(path.dirname(require.resolve('terriajs-cesium/package.json')), 'Source'),
        loader: require.resolve('./removeCesiumDebugPragmas')
    });

    // Don't let Cesium's `buildModuleUrl` see require - only the AMD version is relevant.
    config.module.loaders.push({
        test: require.resolve('terriajs-cesium/Source/Core/buildModuleUrl'),
        loader: 'imports-loader?require=>false'
    });

    // Don't let Cesium's `crunch.js` see require - only the AMD version is relevant.
    config.module.loaders.push({
        test: require.resolve('terriajs-cesium/Source/ThirdParty/crunch'),
        loader: 'imports-loader?require=>false'
    });

    config.module.loaders.push({
        test: /\.(png|jpg|svg|gif)$/,
        include: [
            path.resolve(terriaJSBasePath),
            path.resolve(cesiumDir)
        ],
        exclude: [
            path.resolve(terriaJSBasePath, 'wwwroot', 'images', 'icons'),
            path.resolve(terriaJSBasePath, 'wwwroot', 'fonts')
        ],
        loader: 'url-loader',
        query: {
            limit: 8192
        }
    });

    config.module.loaders.push({
        test: /\.woff(2)?(\?.+)?$/,
        include: path.resolve(terriaJSBasePath, 'wwwroot', 'fonts'),
        loader: 'url-loader',
        query: {
            limit: 10000,
            mimetype: 'application/font-woff'
        }
    });

    config.module.loaders.push({
        test: /\.(ttf|eot|svg)(\?.+)?$/,
        include: path.resolve(terriaJSBasePath, 'wwwroot', 'fonts'),
        loader: 'file-loader'
    });

    config.module.loaders.push({
        test: /\.svg$/,
        include: path.resolve(terriaJSBasePath, 'wwwroot', 'images', 'icons'),
        loader: 'svg-sprite-loader'
    });

    config.devServer = config.devServer || {
        stats: 'minimal',
        port: 3003,
        contentBase: 'wwwroot/',
        proxy: {
            '*': {
                target: 'http://localhost:3001',
                bypass: function (req, res, proxyOptions) {
                    if (req.url.indexOf('/proxy') < 0 &&
                        req.url.indexOf('/proj4lookup') < 0 &&
                        req.url.indexOf('/convert') < 0 &&
                        req.url.indexOf('/proxyabledomains') < 0 &&
                        req.url.indexOf('/errorpage') < 0 &&
                        req.url.indexOf('/init') < 0 &&
                        req.url.indexOf('/serverconfig') < 0) {
                        return req.originalUrl;
                    }
                }
            }
        },
    };

    config.plugins = (config.plugins || []).concat([
        new StringReplacePlugin()
    ]);

    if (hot && !disableStyleLoader) {
        config.module.loaders.push({
            include: path.resolve(terriaJSBasePath),
            test: /\.scss$/,
            loaders: [
                'style-loader',
                {
                    loader: 'css-loader',
                    options: {
                        sourceMap: true,
                        modules: true,
                        camelCase: true,
                        localIdentName: 'tjs-[name]__[local]',
                        importLoaders: 2
                    }
                },
                'resolve-url-loader?sourceMap',
                'sass-loader?sourceMap'
            ]
        });
    } else if (ExtractTextPlugin) {
        config.module.loaders.push({
            exclude: path.resolve(terriaJSBasePath, 'lib', 'Sass'),
            include: path.resolve(terriaJSBasePath, 'lib'),
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract({
                use: [
                    {
                        loader: 'css-loader',
                        options: {
                            sourceMap: true,
                            modules: true,
                            camelCase: true,
                            localIdentName: 'tjs-[name]__[local]',
                            importLoaders: 2
                        }
                    },
                    'resolve-url-loader?sourceMap',
                    'sass-loader?sourceMap'
                ],
                publicPath: ''
            })
        });
    }

    config.resolve = config.resolve || {};
    config.resolve.alias = config.resolve.alias || {};

    // Make a terriajs-variables alias so it's really easy to override our sass variables by aliasing over the top of this.
    config.resolve.alias['terriajs-variables'] = config.resolve.alias['terriajs-variables'] || require.resolve('../lib/Sass/common/_variables.scss');

    // Alias react and react-dom to the one used by the building folder - apparently we can rely on the dir always being
    // called node_modules https://github.com/npm/npm/issues/2734
    config.resolve.alias['react'] = path.dirname(require.resolve('react'));
    config.resolve.alias['react-dom'] = path.dirname(require.resolve('react-dom'));

    return config;
}
module.exports = Request.get(LIST_MODULES_URL, { json: true }).then(function (data) {
  var modules = data.modules;

  return {
    entry: './webtask',
    output: {
      path: './build/server',
      filename: 'bundle.js',
      library: true,
      libraryTarget: 'commonjs2',
    },
    module: {
      loaders: [
         {
          test: /\.jade$/,
          loader: StringReplacePlugin.replace({
            replacements: [
              {
                pattern: /@assets_baseurl/ig,
                replacement: function (match, p1, offset, string) {
                  var location = 'http://localhost:3000';

                  if ((process.env.NODE_ENV || 'development') !== 'development') {
                    location = 'https://cdn.auth0.com/extensions/' + pkg.name + '/assets';
                  }

                  return location;
                }.bind(this)
              },
              {
                pattern: /@extension_name/ig,
                replacement: function (match, p1, offset, string) {
                  return pkg.name + '-' + pkg.version;
                }.bind(this)
              }
            ]
          })
        },
        { test: /\.jade$/, loader: require.resolve('jade-loader') },
        {
          test: /\.json?$/,
          loader: 'json'
        }
      ]
    },
    externals: _(modules).reduce(function (acc, module) {
         if (module.name === 'auth0-oauth2-express') {
          return _.set(acc, module.name, false);
        }

        return _.set(acc, module.name, true);
    }, {
      // Not provisioned via verquire
      'auth0-api-jwt-rsa-validation': true,
      'auth0-authz-rules-api': true,
      'auth0-oauth2-express': true,
      'auth0-sandbox-ext': true,
      'detective': true,
      'sandboxjs': true,
      'webtask-tools': true,
    }),
    plugins: [
      new StringReplacePlugin(),
      new Webpack.optimize.DedupePlugin(),
      // new Webpack.optimize.UglifyJsPlugin({
      //   compress: {
      //     warnings: false
      //   }
      // })
    ],
    resolve: {
      modulesDirectories: ['node_modules'],
      root: __dirname,
      alias: {},
    },
    node: false
  };
});
Beispiel #26
0
module.exports = function makeWebpackConfig () {
  /**
   * Config
   * Reference: http://webpack.github.io/docs/configuration.html
   * This is the object where all configuration gets set
   */
  var config = {};

  /**
   * Entry
   * Reference: http://webpack.github.io/docs/configuration.html#entry
   * Should be an empty object if it's generating a test build
   * Karma will set this when it's a test build
   */
  config.entry = isTest ? {} : {
    app: './src/index.js'
  };

  var serverPort = process.env.SERVER_PORT || 8080;
  var webPort = process.env.WEB_PORT || 9000;

  /**
   * Output
   * Reference: http://webpack.github.io/docs/configuration.html#output
   * Should be an empty object if it's generating a test build
   * Karma will handle setting it up for you when it's a test build
   */
  config.output = isTest ? {} : {
    // Absolute output directory
    path: __dirname + '/dist',

    // Output path from the view of the page
    // Uses webpack-dev-server in development
    publicPath: isProd ? '' : 'http://localhost:' + webPort + '/',

    // Filename for entry points
    // Only adds hash in build mode
    filename: isProd ? '[name].[hash].js' : '[name].bundle.js',

    // Filename for non-entry points
    // Only adds hash in build mode
    chunkFilename: isProd ? '[name].[hash].js' : '[name].bundle.js'
  };

  /**
   * Devtool
   * Reference: http://webpack.github.io/docs/configuration.html#devtool
   * Type of sourcemap to use per build type
   */
  if (isTest) {
    config.devtool = 'inline-source-map';
  } else if (isProd) {
    config.devtool = 'source-map';
  } else {
    config.devtool = 'eval-source-map';
  }
  config.devtool = 'source-map';

  /**
   * Loaders
   * Reference: http://webpack.github.io/docs/configuration.html#module-loaders
   * List: http://webpack.github.io/docs/list-of-loaders.html
   * This handles most of the magic responsible for converting modules
   */

  // Initialize module
  config.module = {
    preLoaders: [],
    loaders: [{
      // JS LOADER
      // Reference: https://github.com/babel/babel-loader
      // Transpile .js files using babel-loader
      // Compiles ES6 and ES7 into ES5 code
      test: /\.js$/,
      loaders: ['ng-annotate', 'babel-loader'],
      exclude: /(node_modules|bower_components)/,
    }, {
      // CSS LOADER
      // Reference: https://github.com/webpack/css-loader
      // Allow loading css through js
      //
      // Reference: https://github.com/postcss/postcss-loader
      // Postprocess your css with PostCSS plugins
      test: /\.css$/,
      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files in production builds
      //
      // Reference: https://github.com/webpack/style-loader
      // Use style-loader in development.
      loader: isTest ? 'null' : ExtractTextPlugin.extract('style-loader', 'css-loader?sourceMap!postcss-loader')
    }, {
      // ASSET LOADER
      // Reference: https://github.com/webpack/file-loader
      // Copy png, jpg, jpeg, gif, svg, woff, woff2, ttf, eot files to output
      // Rename the file using the asset hash
      // Pass along the updated reference to your code
      // You can add here any file extension you want to get copied to your output
      test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/,
      loader: 'file'
    }, {
      // HTML LOADER
      // Reference: https://github.com/webpack/raw-loader
      // Allow loading html through js
      test: /\.html$/,
      loader: 'raw'
    }, {
      // STRING REPLACE PLUGIN
      // reference: https://www.npmjs.com/package/string-replace-webpack-plugin
      // Allow for arbitrary strings to be replaced as part of the module build process
      // Configure replacements for file patterns
      test: /index.html$/,
      loader: stringReplacePlugin.replace({
        replacements: [{
          pattern: /WEB_PORT/ig,
          replacement: function (match, p1, offset, string) {
            return webPort;
          }
        }
      ]})
    }]
  };

  /**
   * PostCSS
   * Reference: https://github.com/postcss/autoprefixer-core
   * Add vendor prefixes to your css
   */
  config.postcss = [
    autoprefixer({
      browsers: ['last 2 version']
    })
  ];

  /**
   * Plugins
   * Reference: http://webpack.github.io/docs/configuration.html#plugins
   * List: http://webpack.github.io/docs/list-of-plugins.html
   */
  config.plugins = [
  ];

  // Skip rendering index.html in test mode
  if (!isTest) {
    // Reference: https://github.com/ampedandwired/html-webpack-plugin
    // Render index.html
    config.plugins.push(
      new HtmlWebpackPlugin({
        template: './src/index.html',
        inject: 'body'
      }),

      // Reference: https://github.com/webpack/extract-text-webpack-plugin
      // Extract css files
      // Disabled when in test mode or not in build mode
      new ExtractTextPlugin('[name].[hash].css', {disable: !isProd}),

      // Reference: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
      new webpack.DefinePlugin({
        'process.env': {
          HELIUM_BUNDLE_DEV: process.env.HELIUM_BUNDLE_DEV,
          SERVER_PORT: serverPort,
          WEB_PORT: webPort
        }
      })
    )
  }

  // Add build specific plugins
  if (isProd) {
    config.plugins.push(
      // Reference: http://webpack.github.io/docs/list-of-plugins.html#noerrorsplugin
      // Only emit files when there are no errors
      new webpack.NoErrorsPlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#dedupeplugin
      // Dedupe modules in the output
      new webpack.optimize.DedupePlugin(),

      // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
      // Minify all javascript, switch loaders to minimizing mode
      new webpack.optimize.UglifyJsPlugin({
        mangle: { screw_ie8: true },
        preserveComments: 'some',
        compress: {
          screw_ie8: true,
          warnings: false,
          sequences: true,
          dead_code: true,
          conditionals: true,
          booleans: true,
          unused: true,
          if_return: true,
          join_vars: true,
          drop_console: true,
        }
      }),

      // Copy assets from the public folder
      // Reference: https://github.com/kevlened/copy-webpack-plugin
      new CopyWebpackPlugin([])
    )
  } else {
    config.plugins.push(
      new InsertLiveReloadPlugin(),
      // reference: https://www.npmjs.com/package/string-replace-webpack-plugin
      new stringReplacePlugin()
    )
  }

  /**
   * Dev server configuration
   * Reference: http://webpack.github.io/docs/configuration.html#devserver
   * Reference: http://webpack.github.io/docs/webpack-dev-server.html
   */
  config.devServer = {
    historyApiFallback: true,
    port: webPort,
    inline: true,
    hot: true,
    progress: true,
    contentBase: './src',
    setup: function(app) {
      app.use('**/bower_components/', express.static(path.resolve(__dirname, './bower_components/')));
      app.use('**/app/', express.static(path.resolve(__dirname, './src/app/')));
      app.use('**/assets/', express.static(path.resolve(__dirname, './src/assets/')));
      app.use('**/fonts/', express.static(path.resolve(__dirname, './src/fonts/')));
      app.use('**/components/', express.static(path.resolve(__dirname, './src/components/')));
    },
    stats: 'minimal',
  };

  return config;
}();
function configureWebpack(terriaJSBasePath, config, devMode, hot, ExtractTextPlugin, disableStyleLoader) {
    const cesiumDir = path.dirname(require.resolve('terriajs-cesium/package.json'));

    config.resolve = config.resolve || {};
    config.resolve.extensions = config.resolve.extensions || ['', '.webpack.js', '.web.js', '.js'];
    config.resolve.extensions.push('.jsx');
    config.resolve.alias = config.resolve.alias || {};
    config.resolve.root = config.resolve.root || [];
    config.resolve.root.push(path.resolve(terriaJSBasePath, 'wwwroot'));

    config.module = config.module || {};
    config.module.loaders = config.module.loaders || [];

    config.module.loaders.push({
        test: /\.js?$/,
        include: path.dirname(require.resolve('terriajs-cesium')),
        exclude: [
            require.resolve('terriajs-cesium/Source/ThirdParty/zip'),
            require.resolve('terriajs-cesium/Source/Core/buildModuleUrl'),
            require.resolve('terriajs-cesium/Source/Core/TaskProcessor')
        ],
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /buildModuleUrl\([\'|\"](.*)[\'|\"]\)/ig,
                    replacement: function (match, p1, offset, string) {
                        return "require('" + cesiumDir.replace(/\\/g, '\\\\') + "/Source/" + p1.replace(/\\/g, '\\\\') + "')";
                    }
                }
            ]
        })
    });

    config.module.loaders.push({
        test: /\.js?$/,
        include: require.resolve('terriajs-cesium/Source/ThirdParty/zip'),
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /new Worker\(obj\.zip\.workerScriptsPath \+(.*)\)/ig,
                    replacement: function (match, p1, offset, string) {
                        return "require('" + require.resolve('worker-loader').replace(/\\/g, '\\\\') + "!" + cesiumDir.replace(/\\/g, '\\\\') + "/Source/ThirdParty/Workers/' + " + p1.replace(/\\/g, '\\\\') + ")()";
                    }
                }
            ]
        })
    });

    config.module.loaders.push({
        test: /\.js?$/,
        include: path.resolve(cesiumDir, 'Source', 'ThirdParty', 'Workers'),
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: "})(this)",
                    replacement: function (match, p1, offset, string) {
                        return "})(self)";
                    }
                }
            ]
        })
    });

    config.module.loaders.push({
        test: /\.js?$/,
        include: require.resolve('terriajs-cesium/Source/Core/TaskProcessor'),
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /new Worker\(getBootstrapperUrl\(\)\)/ig,
                    replacement: function (match, p1, offset, string) {
                        return "require('" + require.resolve('worker-loader').replace(/\\/g, '\\\\') + "!" + require.resolve('../lib/cesiumWorkerBootstrapper').replace(/\\/g, '\\\\') + "')()";
                    }
                },
                {
                    pattern: "new Worker(getWorkerUrl('Workers/transferTypedArrayTest.js'))",
                    replacement: function (match, p1, offset, string) {
                        return "require('" + require.resolve('worker-loader').replace(/\\/g, '\\\\') + "!" + cesiumDir.replace(/\\/g, '\\\\') + "/Source/Workers/transferTypedArrayTest.js')()";
                    }
                }
            ]
        })
    });

    config.module.loaders.push({
        test: /\.js?$/,
        include: path.resolve(cesiumDir, 'Source', 'Workers'),
        loader: StringReplacePlugin.replace({
            replacements: [
                {
                    pattern: /require\(\'Workers\/\' \+ moduleName\)/ig,
                    replacement: function (match, p1, offset, string) {
                        return "require('./' + moduleName)";
                    }
                }
            ]
        })
    });

    // Use Babel to compile our JavaScript files.
    config.module.loaders.push({
        test: /\.jsx?$/,
        include: [
            path.resolve(terriaJSBasePath, 'lib'),
            path.resolve(terriaJSBasePath, 'test')
        ],
        loader: require.resolve('babel-loader'),
        query: {
            sourceMap: false, // generated sourcemaps are currently bad, see https://phabricator.babeljs.io/T7257
            presets: ['es2015', 'react'],
            plugins: [
                require.resolve('jsx-control-statements')
            ]
        }
    });

    //

    // Use the raw loader for our view HTML.  We don't use the html-loader because it
    // will doing things with images that we don't (currently) want.
    config.module.loaders.push({
        test: /\.html$/,
        include: path.resolve(terriaJSBasePath, 'lib', 'Views'),
        loader: require.resolve('raw-loader')
    });

    // Allow XML in the models directory to be required-in as a raw text.
    config.module.loaders.push({
        test: /\.xml$/,
        include: path.resolve(terriaJSBasePath, 'lib', 'Models'),
        loader: require.resolve('raw-loader')
    });

    config.module.loaders.push({
        test: /\.json|xml$/,
        loader: require.resolve('file-loader'),
        include: path.resolve(cesiumDir, 'Source', 'Assets')
    });

    config.module.loaders.push({
        test: /\/Workers\/$/,
        loader: require.resolve('file-loader'),
        include: cesiumDir
    });

    var externalModulesWithJson = ['proj4/package.json', 'entities', 'html-to-react', 'ent', 'htmlparser2/package.json']
        .map(function(module) {
           try {
               return path.dirname(require.resolve(module));
           } catch (e) {
               console.warn('Could not resolve module "' + module + ". Possibly this is no longer a dep of the project?");
           }
        }).filter(function(resolvedModule) {
            return !!resolvedModule;
        });

    config.module.loaders.push({
        test: /\.json$/,
        include: externalModulesWithJson,
        loader: require.resolve('json-loader')
    });

    config.module.loaders.push({
        test: /\.js$/,
        include: path.resolve(path.dirname(require.resolve('terriajs-cesium/package.json')), 'Source'),
        loader: require.resolve('./removeCesiumDebugPragmas')
    });

    // Don't let Cesium's `buildModuleUrl` and `TaskProcessor` see require - only the AMD version is relevant.
    config.module.loaders.push({
        test: require.resolve('terriajs-cesium/Source/Core/buildModuleUrl'),
        loader: require.resolve('imports-loader') + '?require=>false'
    });

    config.module.loaders.push({
        test: /\.(png|jpg|svg|gif)$/,
        include: [
            path.resolve(terriaJSBasePath),
            path.resolve(cesiumDir)
        ],
        exclude: [
            path.resolve(terriaJSBasePath, 'wwwroot', 'images', 'icons'),
            path.resolve(terriaJSBasePath, 'wwwroot', 'fonts')
        ],
        loader: require.resolve('url-loader'),
        query: {
            limit: 8192
        }
    });

    config.module.loaders.push({
        test: /\.woff(2)?(\?.+)?$/,
        include: path.resolve(terriaJSBasePath, 'wwwroot', 'fonts'),
        loader: require.resolve('url-loader'),
        query: {
            limit: 10000,
            mimetype: 'application/font-woff'
        }
    });

    config.module.loaders.push({
        test: /\.(ttf|eot|svg)(\?.+)?$/,
        include: path.resolve(terriaJSBasePath, 'wwwroot', 'fonts'),
        loader: require.resolve('file-loader')
    });

    config.module.loaders.push({
        test: /\.svg$/,
        include: path.resolve(terriaJSBasePath, 'wwwroot', 'images', 'icons'),
        loader: require.resolve('svg-sprite-loader')
    });

    config.devServer = config.devServer || {
        stats: 'minimal',
        port: 3003,
        contentBase: 'wwwroot/',
        proxy: {
            '*': {
                target: 'http://localhost:3001',
                bypass: function (req, res, proxyOptions) {
                    if (req.url.indexOf('/proxy') < 0 &&
                        req.url.indexOf('/proj4lookup') < 0 &&
                        req.url.indexOf('/convert') < 0 &&
                        req.url.indexOf('/proxyabledomains') < 0 &&
                        req.url.indexOf('/errorpage') < 0 &&
                        req.url.indexOf('/init') < 0 &&
                        req.url.indexOf('/serverconfig') < 0) {
                        return req.originalUrl;
                    }
                }
            }
        },
    };

    config.plugins = (config.plugins || []).concat([
        new StringReplacePlugin()
    ]);

    if (hot && !disableStyleLoader) {
        config.module.loaders.push({
            include: path.resolve(terriaJSBasePath),
            test: /\.scss$/,
            loaders: [
                require.resolve('style-loader'),
                require.resolve('css-loader') + '?sourceMap&modules&camelCase&localIdentName=tjs-[name]__[local]&importLoaders=2',
                require.resolve('resolve-url-loader') + '?sourceMap',
                require.resolve('sass-loader') + '?sourceMap'
            ]
        });
    } else if (ExtractTextPlugin) {
        config.module.loaders.push({
            exclude: path.resolve(terriaJSBasePath, 'lib', 'Sass'),
            include: path.resolve(terriaJSBasePath, 'lib'),
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract(
                require.resolve('css-loader') + '?sourceMap&modules&camelCase&localIdentName=tjs-[name]__[local]&importLoaders=2!' +
                require.resolve('resolve-url-loader') + '?sourceMap!' +
                require.resolve('sass-loader') + '?sourceMap',
                {
                    publicPath: ''
                }
            )
        });
    }

    config.resolve = config.resolve || {};
    config.resolve.alias = config.resolve.alias || {};

    // Make a terriajs-variables alias so it's really easy to override our sass variables by aliasing over the top of this.
    config.resolve.alias['terriajs-variables'] = config.resolve.alias['terriajs-variables'] || require.resolve('../lib/Sass/common/_variables.scss');

    // Alias react and react-dom to the one used by the building folder - apparently we can rely on the dir always being
    // called node_modules https://github.com/npm/npm/issues/2734
    config.resolve.alias['react'] = path.dirname(require.resolve('react'));
    config.resolve.alias['react-dom'] = path.dirname(require.resolve('react-dom'));

    return config;
}
       loader: 'babel',
       query: {
         presets: [ 'es2015', 'stage-0' ]
       }
     },
     {
       test: /\.json$/,
       loader: 'json'
     },
     {
       test: /validate.js$/,
       include: /node_modules\/json-schema/,
       loader: StringReplacePlugin.replace({ // from the 'string-replace-webpack-plugin'
         replacements: [{
           pattern: /\(\{define:typeof define!="undefined"\?define:function\(deps, factory\)\{module\.exports = factory\(\);\}\}\)\./ig,
           replacement: function(match, p1, offset, string) {
             return false;
           }
         }]
       })
     }
   ]
 },
 plugins: [
   // https://github.com/andris9/encoding/issues/16
   new NormalModuleReplacementPlugin(/\/iconv-loader$/, 'node-noop'),
   new StringReplacePlugin(),
   // https://github.com/visionmedia/superagent/wiki/Superagent-for-Webpack
   new DefinePlugin(defines),
 ],
 // From: https://github.com/webpack/webpack/issues/784
 // for modules
Beispiel #29
0
function config(grunt) {
    const date = grunt.config.get('date');
    const dt = date.toISOString().replace(/T.*/, '');
    const year = date.getFullYear();
    return {
        mode: 'production',
        entry: {
            app: 'app',
            vendor: ['jquery', 'underscore', 'backbone', 'kdbxweb', 'baron',
                'pikaday', 'jsqrcode', 'argon2-wasm', 'argon2']
        },
        output: {
            path: path.resolve('.', 'tmp/js'),
            filename: '[name].js'
        },
        target: 'web',
        performance: {
            hints: false
        },
        stats: {
            colors: false,
            modules: true,
            reasons: true
        },
        progress: false,
        failOnError: true,
        resolve: {
            modules: [path.join(__dirname, 'app/scripts'), path.join(__dirname, 'node_modules')],
            alias: {
                backbone: 'backbone/backbone-min.js',
                underscore: 'underscore/underscore-min.js',
                _: 'underscore/underscore-min.js',
                jquery: 'jquery/dist/jquery.min.js',
                kdbxweb: 'kdbxweb/dist/kdbxweb.js',
                baron: 'baron/baron.min.js',
                pikaday: 'pikaday/pikaday.js',
                qrcode: 'jsqrcode/dist/qrcode.min.js',
                argon2: 'argon2-browser/dist/argon2.min.js',
                hbs: 'handlebars/runtime.js',
                'argon2-wasm': 'argon2-browser/dist/argon2.wasm',
                templates: path.join(__dirname, 'app/templates')
            }
        },
        module: {
            rules: [
                {
                    test: /\.hbs$/, loader: StringReplacePlugin.replace('handlebars-loader', {
                        replacements: [{ pattern: /\r?\n\s*/g, replacement: () => '\n' }]
                    })
                },
                {
                    test: /runtime-info\.js$/, loader: StringReplacePlugin.replace({
                        replacements: [
                            { pattern: /@@VERSION/g, replacement: () => pkg.version + (grunt.option('beta') ? '-beta' : '') },
                            { pattern: /@@BETA/g, replacement: () => grunt.option('beta') ? '1' : '' },
                            { pattern: /@@DATE/g, replacement: () => dt },
                            { pattern: /@@COMMIT/g, replacement: () => grunt.config.get('gitinfo.local.branch.current.shortSHA') }
                        ]
                    })
                },
                {test: /baron(\.min)?\.js$/, loader: 'exports-loader?baron; delete window.baron;'},
                {test: /pikaday\.js$/, loader: 'uglify-loader'},
                {test: /handlebars/, loader: 'strip-sourcemap-loader'},
                {
                    test: /\.js$/, exclude: /(node_modules)/, loader: 'babel-loader',
                    query: {presets: ['@babel/preset-env'], cacheDirectory: true}
                },
                {test: /argon2\.wasm/, type: 'javascript/auto', loader: 'base64-loader'},
                {test: /argon2(\.min)?\.js/, loader: 'raw-loader'},
                {test: /\.scss$/, loader: 'raw-loader'}
            ]
        },
        optimization: {
            runtimeChunk: 'single',
            splitChunks: {
                cacheGroups: {
                    vendor: {
                        test: /[\\/]node_modules[\\/]/,
                        name: 'vendor',
                        chunks: 'all'
                    }
                }
            },
            minimizer: [
                new UglifyJsPlugin({
                    cache: true,
                    parallel: true
                }),
                new BundleAnalyzerPlugin({
                    openAnalyzer: false,
                    analyzerMode: 'static',
                    reportFilename: '../stats/analyzer_report.html',
                    generateStatsFile: true,
                    statsFilename: '../stats/stats.json'
                })
            ]
        },
        plugins: [
            new webpack.BannerPlugin('keeweb v' + pkg.version + ', (c) ' + year + ' ' + pkg.author.name +
                ', opensource.org/licenses/' + pkg.license),
            new webpack.ProvidePlugin({_: 'underscore', $: 'jquery'}),
            new webpack.IgnorePlugin(/^(moment)$/),
            new StringReplacePlugin()
        ],
        node: {
            console: false,
            process: false,
            crypto: false,
            Buffer: false,
            __filename: false,
            __dirname: false,
            fs: false,
            setImmediate: false,
            path: false
        },
        externals: {
            xmldom: 'null',
            crypto: 'null',
            fs: 'null',
            path: 'null'
        }
    };
}
module.exports = function (env = {}) {
  const extractSass = new ExtractTextPlugin({
    filename: 'styles.css'
  })

  const plugins = (() => {
    const pluginsArray = [
      extractSass,

      new CleanWebpackPlugin('build'),
      new HtmlWebpackPlugin({template: './src/index.hbs'}),
      new StringReplacePlugin(),
      new ImageminPlugin({
                // disable: !env.production,
        plugins: [
          imageminMozjpeg({
            quality: 40,
            progressive: true
          })
        ]
      }),
      new FaviconsWebpackPlugin({
        logo: './src/images/logo.png',
        title: 'albinotonnina.com'
      })
    ]

    if (env.production) {
      pluginsArray.push(new webpack.optimize.UglifyJsPlugin())

      if (env.production.stats) {
        pluginsArray.push(new BundleAnalyzerPlugin({
          analyzerMode: 'static'
        }))
      }
    }

    return pluginsArray
  })()

  return {
    devtool: 'source-map',
    entry: './src/index.js',
    output: {
      path: path.resolve(__dirname, 'build'),
      filename: 'bundle.js'
    },
    plugins,
    devServer: {
      contentBase: path.join(__dirname, 'build'),
      compress: true,
      port: 4000,
      host: '0.0.0.0',
      open: true,
      inline: true
    },
    module: {
      rules: [
        {
          test: /\.hbs$/,
          loader: 'handlebars-loader',
          query: {
            partialDirs: [
              path.join(__dirname, 'src')
            ],
            inlineRequires: '/images/'
          }
        },
        {
          test: /\.js$/,
          exclude: /(node_modules)/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true
            }
          }
        },
        {
          test: /\.scss$/,
          use: extractSass.extract({
            use: [{
              loader: 'raw-loader'
            }, {
              loader: 'sass-loader'
            }]
          })
        },

        {
          test: /\.html$/,
          use: ['html-loader']
        },
        {
          test: /\.(png|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader'
            }
          ]
        },
        {
          test: /\.svg$/,
          loader: 'svg-inline-loader?classPrefix'
        },
        {
          test: /\.svg$/,
          loader: StringReplacePlugin.replace({
            replacements: [
              {
                pattern: /font-family="'Roboto-Thin'"/ig,
                replacement: () => 'font-weight="100"'
              },
              {
                pattern: /font-family="'Roboto-Light'"/ig,
                replacement: () => 'font-weight="300"'
              },
              {
                pattern: /font-family="'Roboto-Regular'"/ig,
                replacement: () => 'font-weight="400"'
              },
              {
                pattern: /font-family="'Roboto-Black'"/ig,
                replacement: () => 'font-weight="900"'
              }
            ]
          })
        }
      ]
    }
  }
}