Skip to content

Instantly share code, notes, and snippets.

@caraya
Last active December 20, 2017 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caraya/a3590e4da5b3fa26740228a0e188c0ff to your computer and use it in GitHub Desktop.
Save caraya/a3590e4da5b3fa26740228a0e188c0ff to your computer and use it in GitHub Desktop.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Globalize App example using Webpack</title>
</head>
<body>
<h1>Globalize App example using Webpack</h1>
<div id="requirements">
<h2>Requirements</h2>
<ul>
<li>Read README.md for instructions on how to run the demo.
</li>
</ul>
</div>
<div id="demo" style="display: none">
<p id="intro-1">Use Globalize to internationalize your application.</p>
<table border="1" style="margin-bottom: 1em;">
<tbody>
<tr>
<td><span id="number-label">Standalone Number</span></td>
<td>"<span id="number"></span>"</td>
</tr>
<tr>
<td><span id="currency-label">Standalone Currency</span></td>
<td>"<span id="currency"></span>"</td>
</tr>
<tr>
<td><span id="date-label">Standalone Date</span></td>
<td>"<span id="date"></span>"</td>
</tr>
<tr>
<td><span id="date-time-zone-label">Standalone Date (in a specific IANA time zone, e.g., America/Los_Angeles)</span></td>
<td>"<span id="date-time-zone"></span>"</td>
</tr>
<tr>
<td><span id="date-to-parts-label">Standalone Date (note the highlighted month, the markup was added using formatDateToParts)</span></td>
<td>"<span id="date-to-parts"></span>"</td>
</tr>
<tr>
<td><span id="relative-time-label">Standalone Relative Time</span></td>
<td>"<span id="relative-time"></span>"</td>
</tr>
<tr>
<td><span id="unit-label">Standalone Unit</span></td>
<td>"<span id="unit"></span>"</td>
</tr>
</tbody>
</table>
<p id="message-1">
An example of a message using mixed number "{number}", currency "{currency}", date "{date}", relative time "{relativeTime}", and unit "{unit}".
</p>
<p id="message-2">
An example of a message with pluralization support:
{count, plural,
one {You have one remaining task}
other {You have # remaining tasks}
}.
</p>
</div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js');
});
}
</script>
{%
var hasShownLocaleHelp;
for ( var chunk in o.htmlWebpackPlugin.files.chunks ) {
if ( /globalize-compiled-data-/.test( chunk ) && chunk !== "globalize-compiled-data-en" ) {
if ( !hasShownLocaleHelp ) {
hasShownLocaleHelp = true;
%}
<!--
Load support for the `en` (English) locale.
For displaying the application in a different locale, replace `en` with
whatever other supported locale you want, e.g., `pt` (Portuguese).
For supporting additional locales simultaneously and then having your
application to change it dynamically, load the multiple files here. Then,
use `Globalize.locale( <locale> )` in your application to dynamically set
it.
-->
{% } %}
<!-- <script src="{%=o.htmlWebpackPlugin.files.chunks[chunk].entry %}"></script> -->
{% } else { %}
<script src="{%=o.htmlWebpackPlugin.files.chunks[chunk].entry %}"></script>
{%
}
}
%}
</body>
</html>
var Globalize = require( "globalize" );
var startTime = new Date();
// Standalone table.
var numberFormatter = Globalize.numberFormatter({ maximumFractionDigits: 2 });
document.getElementById( "number" ).textContent = numberFormatter( 12345.6789 );
var currencyFormatter = Globalize.currencyFormatter( "USD" );
document.getElementById( "currency" ).textContent = currencyFormatter( 69900 );
var dateFormatter = Globalize.dateFormatter({ datetime: "medium" });
document.getElementById( "date" ).textContent = dateFormatter( new Date() );
var dateWithTimeZoneFormatter = Globalize.dateFormatter({
datetime: "full",
timeZone: "America/Los_Angeles"
});
document.getElementById( "date-time-zone" ).textContent = dateWithTimeZoneFormatter( new Date() );
var _dateToPartsFormatter = Globalize.dateToPartsFormatter({ datetime: "medium" });
var dateToPartsFormatter = function( value ) {
return _dateToPartsFormatter( value, {
datetime: "medium"
}).map(function( part ) {
switch(part.type) {
case "month": return "<strong>" + part.value + "</strong>";
default: return part.value;
}
}).reduce(function( memo, value ) {
return memo + value;
});
};
document.getElementById( "date-to-parts" ).innerHTML = dateToPartsFormatter( new Date() );
var relativeTimeFormatter = Globalize.relativeTimeFormatter( "second" );
document.getElementById( "relative-time" ).textContent = relativeTimeFormatter( 0 );
var unitFormatter = Globalize.unitFormatter( "mile/hour", { form: "short" } );
document.getElementById( "unit" ).textContent = unitFormatter( 60 );
// Messages.
document.getElementById( "intro-1" ).textContent = Globalize.formatMessage( "intro-1" );
document.getElementById( "number-label" ).textContent = Globalize.formatMessage( "number-label" );
document.getElementById( "currency-label" ).textContent = Globalize.formatMessage( "currency-label" );
document.getElementById( "date-label" ).textContent = Globalize.formatMessage( "date-label" );
document.getElementById( "date-time-zone-label" ).textContent = Globalize.formatMessage( "date-time-zone-label" );
document.getElementById( "date-to-parts-label" ).textContent = Globalize.formatMessage( "date-to-parts-label" );
document.getElementById( "relative-time-label" ).textContent = Globalize.formatMessage( "relative-time-label" );
document.getElementById( "unit-label" ).textContent = Globalize.formatMessage( "unit-label" );
document.getElementById( "message-1" ).textContent = Globalize.formatMessage( "message-1", {
currency: currencyFormatter( 69900 ),
date: dateFormatter( new Date() ),
number: numberFormatter( 12345.6789 ),
relativeTime: relativeTimeFormatter( 0 ),
unit: unitFormatter( 60 )
});
document.getElementById( "message-2" ).textContent = Globalize.formatMessage( "message-2", {
count: 3
});
// Display demo.
document.getElementById( "requirements" ).style.display = "none";
document.getElementById( "demo" ).style.display = "block";
// Refresh elapsed time
setInterval(function() {
var elapsedTime = +( ( startTime - new Date() ) / 1000 ).toFixed( 0 );
document.getElementById( "date" ).textContent = dateFormatter( new Date() );
document.getElementById( "date-time-zone" ).textContent = dateWithTimeZoneFormatter( new Date() );
document.getElementById( "date-to-parts" ).innerHTML = dateToPartsFormatter( new Date() );
document.getElementById( "relative-time" ).textContent = relativeTimeFormatter( elapsedTime );
document.getElementById( "message-1" ).textContent = Globalize.formatMessage( "message-1", {
currency: currencyFormatter( 69900 ),
date: dateFormatter( new Date() ),
number: numberFormatter( 12345.6789 ),
relativeTime: relativeTimeFormatter( elapsedTime ),
unit: unitFormatter( 60 )
});
}, 1000);
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "webpack-config.js",
"devDependencies": {
"cldr-data": ">=25",
"clean-webpack-plugin": "^0.1.17",
"css-loader": "^0.28.7",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^1.1.5",
"globalize": "^1.3.0",
"globalize-webpack-plugin": "^2.0.1",
"html-webpack-plugin": "^1.1.0",
"iana-tz-data": "^2017.1.0",
"nopt": "^3.0.3",
"skip-amd-webpack-plugin": "^0.2.0",
"style-loader": "^0.19.0",
"webpack": "^3.8.0",
"webpack-bundle-analyzer": "^2.9.1",
"webpack-dev-server": "^2.9.4",
"webpack-manifest-plugin": "^1.3.2",
"webpack-monitor": "^1.0.13",
"workbox-webpack-plugin": "^2.1.1"
},
"Dependencies": {},
"cldr-data-urls-filter": "(core|dates|numbers|units)",
"scripts": {
"start": "webpack-dev-server --config webpack-config.js --hot --progress --colors --inline",
"build": "webpack --display-error-details --config webpack-config.js"
},
"keywords": [],
"author": "",
"license": "MIT"
}
// Require Webpack first
const webpack = require( "webpack" );
// commonsChunkPlugin
const CommonsChunkPlugin = require( "webpack/lib/optimize/CommonsChunkPlugin" );
// HTML Web Pack Plugin
const HtmlWebpackPlugin = require( "html-webpack-plugin" );
// Globalize
const GlobalizePlugin = require( "globalize-webpack-plugin" );
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const nopt = require("nopt");
const path = require('path');
const workboxPlugin = require('workbox-webpack-plugin');
const options = nopt({
production: Boolean
});
module.exports = {
entry: options.production ? {
main: "./app/index.js",
// What files to put in the vendor bundle
vendor: [
"globalize",
"globalize/dist/globalize-runtime/number",
"globalize/dist/globalize-runtime/currency",
"globalize/dist/globalize-runtime/date",
"globalize/dist/globalize-runtime/message",
"globalize/dist/globalize-runtime/plural",
"globalize/dist/globalize-runtime/relative-time",
"globalize/dist/globalize-runtime/unit"
]
} : "./app/index.js",
output: {
//path: options.production ? "./dist" : "./tmp",
pathinfo: true,
filename: '[name].bundle.js',
chunkFilename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: options.production ? "" : "http://localhost:8080/"
},
resolve: {
// Consider the following extensions to be javascript
extensions: [
".es6",
".js",
".ts"
]
},
// Performance budget, maxAssetSize include individual bundles
// maxEntryPointSize referes to combined file size
performance: {
maxAssetSize: 100000,
maxEntrypointSize: 300000,
hints: 'warning'
},
module: {
loaders: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{ test: /\.png$/, loader: "file-loader" }
]
},
plugins: [
// Debug mode on!
new webpack.LoaderOptionsPlugin({
debug: true
}),
// Generate manifest.json file in your root output directory
// with a mapping of all source file names to their corresponding output file,
new ManifestPlugin(),
// Clean up the dist directory before we put stuff in it
new CleanWebpackPlugin(['dist']),
// Bundle Analyzer. See https://www.npmjs.com/package/webpack-bundle-analyzer
// for more instructions
new BundleAnalyzerPlugin({
// Can be `server`, `static` or `disabled`.
// Static option will generate a report.html file
analyzerMode: 'static',
// Host that will be used in `server` mode to start HTTP server.
analyzerHost: '127.0.0.1',
// Port that will be used in `server` mode to start HTTP server.
analyzerPort: 8888,
// Path to bundle report file that will be generated in `static` mode. Relative to bundles output directory.
reportFilename: 'report.html',
// Module sizes to show in report by default. Should be one of `stat`, `parsed` or `gzip`.
defaultSizes: 'gzip',
// Whether to automatically open report in default browser
openAnalyzer: false,
// If `true`, Webpack Stats JSON file will be generated in bundles output directory
generateStatsFile: true,
// Name of Webpack Stats JSON file that will be generated if `generateStatsFile` is `true`.
// Relative to bundles output directory.
statsFilename: 'stats.json',
// Options for `stats.toJson()` method.
// See options in: https://github.com/webpack/webpack/blob/webpack-1/lib/Stats.js#L21
statsOptions: null,
// Log level. Can be 'info', 'warn', 'error' or 'silent'.
logLevel: 'info'
}),
// Extracts CSS from files into a css bundle
new ExtractTextPlugin({
filename: "style.css"
}),
// generates a file with proper links to bundles from a template
// in the root directory
new HtmlWebpackPlugin({
production: options.production,
template: "./index-template.html"
}),
// Run Globalize's tasks
new GlobalizePlugin({
production: options.production,
developmentLocale: "en",
supportedLocales: [ "ar", "de", "en", "es", "pt", "ru", "zh" ],
messages: "messages/[locale].json",
output: "i18n/[locale].[hash].js"
}),
// Create one or more chunks from vendor bundle
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.[hash].js'
}),
// Runs uglify.js
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})//,
// Generates precaching service worker based on our existing directories
// new workboxPlugin({
// globDirectory: "./dist",
// globPatterns: ['**/*.{html,css,js}'],
// swDest: "./dist/sw.js",
// clientsClaim: true,
// skipWaiting: true,
// })
]
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment