Momentjs-introduction
提供:Dev Guides
MomentJS-はじめに
この章では、RequireJS と *MomentJSとTypeScript を使用して* MomentJSを操作する方法について説明します。
MomentJSおよびRequireJS
RequireJSを使用したMomentJSの動作を理解するために、MomentJSとRequireJSを使用した動作例を分析してみましょう。 対応するアプリのフォルダ構造は、次の画像に示されています-
RequireJS公式サイトから取得したrequire.jsファイルを取得できます-https://requirejs.org/docs/downloadl[[[1]]]理解を深めるために次のコードを確認してください-
プロジェクトの例
<!DOCTYPE html>
<html>
<head>
<title>RequireJS and MomentJS</title>
<!-- data-main attribute tells require.js to load
scripts/main.js after require.js loads. -->
<script data-main="scripts/main" src="scripts/require.js"></script>
</head>
<body>
<h1>RequireJS and MomentJS</h1>
<div id="datedisplay" style="font-size:25px;"></div>
</body>
</html>
main.js
require.config({
paths:{
'momentlocale':'libs/momentlocale',
},
});
require(['momentlocale'], function (moment) {
moment.locale('fr');
var a = moment().format("LLLL");
document.getElementById("datedisplay").innerHTML = a;
});
*Moment.js* および *momentlocale.js* は *libs* フォルダーにあることに注意してください。
以下は、ブラウザで確認できる projectl の出力です-
MomentJSおよびTypeScript
MomentJSとTypescriptプロジェクトの構築に使用されるコードは以下のとおりです-
package.json
{
"name": "momenttypescript",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"browserify": "^16.2.0",
"gulp": "^3.9.1",
"gulp-connect": "^5.5.0",
"gulp-typescript": "^4.0.2",
"moment": "^2.22.1",
"tsify": "^4.0.0",
"typescript": "^2.8.3",
"vinyl-source-stream": "^2.0.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
*package、json* で利用可能な依存関係は、npm *install* を使用してインストールする必要があることに注意してください。
main.ts
import * as moment from 'moment';
let now = moment().format('LLLL');
document.getElementById("datedisplay").innerHTML = now;
ファイルをtypescriptからJavaScript、つまり main.ts から main.js にビルドするには、* Gulpを使用する必要があります。 次のコードは、ファイルのビルドに使用される gulpfile .jsを示しています。 ローカルサーバーを開いて出力を表示する gulp-connect パッケージを使用していることに注意してください。
gulpfile.js
var gulp = require("gulp");
var connect = require("gulp-connect");
var browserify = require("browserify");
var tsify = require("tsify");
var source = require("vinyl-source-stream");
gulp.task("build", function (cb) {
runSequence("browserify", "minify", cb);
});
gulp.task("startserver", ["browserify", "connect"]);
gulp.task("browserify", function () {
var b = browserify({
insertGlobals: true,
debug: false
}) .add("src/main.ts") .plugin(tsify, { typescript: require("typescript") });
return b
.bundle()
.pipe(source("main.js"))
.pipe(gulp.dest("build/"));
});
gulp.task("connect", function () {
connect.server({
root: ".",
//port: '80',
livereload: true
});
});
これは、上記のコードを実行したときに観察される出力です-
次の形式で示すように、フォルダ構造を見ることができます-
indexlのコードを以下に示します-
<html>
<head></head>
<body>
<h1>MomentJS and typescript</h1>
<div id="datedisplay" style="font-size:30px;"></div>
<script src="build/main.js"></script>
</body>
</html>
さて、 http://localhost:8080/ を開くと、次のように出力が表示されます-