【AWS DynamoDB】Create tableをPythonで行う
PythonでDynamoDBのテーブルを作成する方法をご紹介します。
(テーブル削除についてはこちら)
リファレンス
boto3を使用できるように、pip install
pip install boto3
create_table.py作成
(今回は例として、「table2」というtableを作成します。カラムは「column1」「column2」「column3」, インデックスは「column1」と「column3」のインデックスを一つ作成します)
import boto3
if __name__ == "__main__":
session = boto3.Session(profile_name='default')
client = session.client('dynamodb', region_name='us-east-2など、地域名')result = client.create_table(
TableName="Table2",
AttributeDefinitions="AttributeDefinitions": [{
"AttributeName": "column1",
"AttributeType": "S"
},
{
"AttributeName": "column2",
"AttributeType": "S"
},
{
"AttributeName": "column3",
"AttributeType": "S"
}
],
KeySchema=[{
"AttributeName": "column1",
"KeyType": "HASH"
},
{
"AttributeName": "column2",
"KeyType": "RANGE"
}
],
LocalSecondaryIndexes=[{
"IndexName": "column1-column3-index",
"KeySchema": [{
"AttributeName": "column1",
"KeyType": "HASH"
},
{
"AttributeName": "column3",
"KeyType": "RANGE"
}
],
"Projection": {
"ProjectionType": "INCLUDE",
"NonKeyAttributes": ["date"]
}]
ProvisionedThroughput={
"ReadCapacityUnits": 15,
"WriteCapacityUnits": 15
})
AttributeDefinitionsでは、使用するカラム名と型を指定します。
今回はcolumn1,2,3を指定しました。(KeySchemaでcolumn1&2, Indexでcolumn3を使用するため。)
※どこにも使用されていないColumn(Column5など)を指定するとエラーになります
※ここで指定していないColumnをKeySchemaやIndexで使用してもエラーになります
GUIで作成したTableを確認すると、下記のように作成できていることがわかります。
KeySchemaのカラム(最大2つまで指定可能)のみ表示されています。
試しにデータを入れてみると、下記のようになります
NoSQLなのでAttributeDefinitionsで指定したカラム名以外のカラム(column7)も入れることができます。KeySchemaのカラム(column1&2)は必須項目になります
Index は下記のようになります
KeySchema(column1&2)に加え、LocalSecondaryIndexesのKeySchema(column3) も表示されています。これてcolumn3の検索が速くなります
以上ですー!!
下記レポジトリでテーブルを削除できるツール(dynamoDB/create_dynamodb_tables_json.py)を作成しましたので、使ってみてください^^
今後もDynamoDBに限らず、 LambdaやAPI Gatewayなど他のAWSサービス用ツールも作成していく予定です。
プルリクなどもいただけると嬉しいです!
おやすみなさい。
【AWS DynamoDB】Delete tableをPythonで行う
PythonでDynamoDBのテーブルを削除する方法をご紹介します。
リファレンス
boto3を使用できるように、pip install
pip install boto3
delete_table.py作成(table1の部分を削除したいテーブル名に変更)
import boto3
if __name__ == "__main__":
session = boto3.Session(profile_name='default')
client = session.client('dynamodb', region_name='us-east-2など、地域名')client.delete_table(TableName=’table1’)
AWS CLIで複数アカウントを管理している場合は、profile_nameで、DynamoDBを操作したいアカウント名を指定してください
操作したいアカウントのregionと、アカウント内DynamoDBを割り当てているregionが違う時のために、region_name引数も指定できるようにしています。
以上ですー!!
下記レポジトリでテーブルを削除できるツール(dynamoDB/delete_all_dynamodb_tables.pyとdelete_dynamodb_tables_yaml.py)を作成しましたので、使ってみてください^^
今後もDynamoDBに限らず、 LambdaやAPI Gatewayなど他のAWSサービス用ツールも作成していく予定です。
プルリクなどもいただけると嬉しいです!
おやすみなさい。
【Nuxt.js & Vue.js】 svgをpngに変換してダウンロード
上記のように、左側のsvgを、pngに変換しダウンロードする方法を紹介します
大まかな流れは、
*imageタグを新規作成
*svg内の描画をBase64形式に変換したものを、上記で作成したimageタグのsrc に設定
*canvas内で上記のimageを描画(キャンバスに一旦描画しないとダウンロードできないため)
*canvasの描画データをBase64形式に変換し、ダウンロードリンクのhrefにセット
画像にしたいsvgの描画については、下記などを参考に!
index.vue
<template>
<div class="row">
<div class="col-6">
<svg id="artboard" xmlns="http://www.w3.org/2000/svg" style="background-color:#ccc" width="500" height="500" viewbox="0 0 500 500"><!-- ここに、画像にしたいsvg描画 -->
</svg>
</div>
<div class="col-6">
<div><button @click="svg2imageData">変換する</button></div>
<canvas id='converted-canvas' width="" height=""></canvas>
<a v-show="show" :href="download_href" id="icon-download" type="application/octet-stream" download="your_icon.png">Download</a>
</div>
</div>
</template>
<script>
export default {
data () {
return {
show: false, // Downloadボタンを隠しておく
download_href: ' ' //Downloadする対象の画像は最初は無し
}
},
methods: {// canvas 内にimage要素を追加するため、image要素を新規作成し、srcを設定する関数
loadImage(src) {
// image作成には時間がかかるため、Promise使用
return new Promise((resolve, reject) => {
// image要素を新規作成
const img = new Image()
// new Image() が成功した場合、作成したimage要素を戻り値にする
img.onload = () => resolve(img)
//new Image() が失敗した場合、エラーメッセージを戻り値にする
img.onerror = (e) => reject(e)
// 引数を作成したimage要素のsrcにセット
img.src = src
})
},// 変換するボタンがクリックされたら呼び出される関数
svg2imageData () {// svgタグ内のelementを取得
const svgElement = document.getElementById('artboard')
// elementからただの文字列に変換
const svgData = new XMLSerializer().serializeToString(svgElement)
// 上記で変換した文字列をbase64形式に変換(canvasが処理できるように)
const imgsrc = 'data:image/svg+xml;charset=utf-8;base64,' + btoa(unescape(encodeURIComponent(svgData)))
// 上記のloadimage関数を実行
this.loadImage(imgsrc).then(img => {//this.loadImageが成功時の処理
// ダウンロードボタンの要素を取得
const downloadBtn = document.getElementById('icon-download')
// ダウンロードボタンを表示するようにする
this.show = true
// キャンバス要素を取得
const canvas = document.getElementById('converted-canvas')
// svgの幅をキャンバスの幅にセット
canvas.width = svgElement.width.baseVal.value
// svgの高さをキャンバスの高さにセット
canvas.height = svgElement.height.baseVal.value
// キャンバス内に画像を描画するため、2Dコンテキストを取得
const ctx = canvas.getContext('2d')
// キャンバス内に、loadimage関数で取得したイメージを描画
ctx.drawImage(img, 0, 0, img.width, img.height)
// キャンバス内に描画したイメージをpng形式のbase64形式で変換し、ダウンロードできるようにdownload_hrefにセット
this.download_href = canvas.toDataURL("image/png")
}).catch(e => {
//this.loadImageでエラー時の処理
console.log('onload error', e)
})
}
}
};</script>
以上ですー!
canvas.toDataURL("image/png")の部分を変更することでjpegなど他の形式や、画質も変更することができます
おやすみなさい
【Python】 違うディレクトリにパスを通す
下記の様なディレクトリ構成で、test1.py を実行する時、別ディレクトリのファイル(common/logger.py)を参照する様にパスを通す方法
.
|____common
| |_logger.py
| |_ __init__.py
|____test
|_ test1.py
|_ __init__.py
common/logger.py: ログを出すための処理を共通化するためのファイル
from logging import getLogger, StreamHandler, Filter, basicConfig, DEBUG
class Log:
def init_logger(name):logger = getLogger(name)
#ログをコンソール出力するための設定
sh = logging.StreamHandler()
logger.addHandler(sh)return logger
test/test1.py
import os
import syssys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.logger import Log
if __name__ == "__main__":
lg = Log.init_logger(__name__)
lg.info('**** TEST1 ****')
これで、python test/test1.pyを実行すると、コンソール上に**** TEST1 **** が表示されます。
上記赤文字の部分が何をしているか、下記で説明:
*__file__: 実行したファイル test/test1.pyを取得
*os.path.dirname(__file__): __file__のディレクトリ test を取得
*os.path.abspath(os.path.dirname(__file__)): testの絶対パス取得(/Users/username/Desktop/~~/repo_root/test)
*os.path.dirname(os.path.abspath(os.path.dirname(__file__))):testの絶対パスのディレクトリ取得
(/Users/username/Desktop/~~/repo_root)
*sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))):検索用パスsys.pathに、
testの絶対パスのディレクトリ(/Users/username/Desktop/~~/repo_root)を登録
上記実行後、sys.pathは下記の様になります。
['/Users/username/Desktop/~~/repo_root/test', '/Users/username/.pyenv/versions/3.7.6/lib/python37.zip', '/Users/username/.pyenv/versions/3.7.6/lib/python3.7', '/Users/username/.pyenv/versions/3.7.6/lib/python3.7/lib-dynload', '/Users/username/.pyenv/versions/3.7.6/lib/python3.7/site-packages', '/Users/username/Desktop/~~/repo_root']
これで、青文字部分
from common.logger import Log
を探しに行くようになります.
まず、sys.pathの上から順に検索するので、
*実行したファイルと同じディレクトリ(/Users/username/Desktop/~~/repo_root/test)内に、common/logger.pyが存在するか見に行きます。
*存在しない場合は、pipなどでインストールしたファイルが格納されているフォルダ内(/Users/username/.pyenv/versions/3.7.6/lib/python37.zipなど)にcommon/logger.pyが存在するか見に行きます。
*更に存在しない場合は、先ほど赤文字部分でappendしたディレクトリ(/Users/username/Desktop/~~/repo_root)見に行きます。
この方法によって、一つ上のディレクトリ配下のファイルを参照できるようになりますー!
更に深くネストしたファイル内で参照する場合はos.path.dirnameを増やすことで、二つ三つ上のディレクトリ配下のファイルも参照できます。
以上です
おやすみなさい
【Nuxt.js & Vue.js】 ドラッグ&ドロップで画像を動かす
Nuxt.js上で、こんな風に、画像をドラッグ&ドロップで動かす方法を紹介していきます。
(Vue.jsも同じ様に実装できるはず)
SVGの使い方については、下記を参考にさせていただきました
1. Circle(円)を動かす
index.vue (青文字部分が、円を描写している部分)
<template>
<svg id="artboard" xmlns="http://www.w3.org/2000/svg" style="background-color:#ccc" width="500" height="500" viewbox="0 0 500 500" @mouseup="dEnd">
<circle class="drag-and-drop" cx=30 cy=30 r=30 fill="blue" @mousedown="mDownCircle" @mousemove="mMoveCircle"/></svg>
</template>
<script>
export default {
data () {
return {
x: 0,
y: 0,
cx: 0,
cy: 0,
r: 0,
is_dragging: false,
},
methods: {
mDownCircle () {// マウスがクリックされたとき、is_draggingをtrueにします
this.is_dragging = true
// クリック時のマウスのX座標とY座標、さらに、circleタグの初期値(cx,cy,r)を変数に格納
this.x = event.pageX
this.y = event.pageY
this.cx = parseInt(event.target.attributes.cx.value)
this.cy = parseInt(event.target.attributes.cy.value)
this.r = parseInt(event.target.attributes.r.value)
},
mMoveCircle () {// マウスがクリックされたまま動かされた(ドラッグ)時に、circleタグのcxとcyの値を変更します。ドラッグが終了する時、一瞬event.pageXとevent.pageYが0になるので、この時は処理しない様にしています。
if (this.is_dragging && event.pageX !== 0 && event.pageY !== 0) {
event.target.setAttribute('cx', event.pageX - this.x + this.cx)
event.target.setAttribute('cy', event.pageY - this.y + this.cy)
}
},dEnd () {
//マウスのドラッグ終了時、変数を初期値に戻しておきます
if (this.is_dragging) {
this.is_dragging = false
this.x = 0
this.y = 0
this.cx = 0
this.cy = 0
this.r = 0
}
}}
これからは、1.の応用で他の図形も動かしていきます
2. Rectangle(四角)
<template>
<svg id="artboard" xmlns="http://www.w3.org/2000/svg" style="background-color:#ccc" width="500" height="500" viewbox="0 0 500 500" @mouseup="dEnd"><rect x="100" y="150" rx="0" ry="0" width="50" height="40" stroke-width="1" stroke="#00FFFF" fill="#CCFFFF" @mousedown="mDownSquare" @mousemove="mMoveSquare"/>
</svg>
</template>
<script>
export default {
data () {
return {
x: 0,
y: 0,
cx: 0,
cy: 0,
r: 0,
is_dragging: false,
},
methods: {mDownSquare () {
this.is_dragging = true
this.x = event.pageX
this.y = event.pageY
this.cx = parseInt(event.target.attributes.x.value)
this.cy = parseInt(event.target.attributes.y.value)
},
mMoveSquare () {
if (this.is_dragging && event.pageX !== 0 && event.pageY !== 0) {
event.target.setAttribute('x', event.pageX - this.x + this.cx)
event.target.setAttribute('y', event.pageY - this.y + this.cy)
}
},dEnd () {
//マウスのドラッグ終了時、変数を初期値に戻しておきます
if (this.is_dragging) {
this.is_dragging = false
this.x = 0
this.y = 0
this.cx = 0
this.cy = 0
}
}}
3. Line(線)
<template>
<svg id="artboard" xmlns="http://www.w3.org/2000/svg" style="background-color:#ccc" width="500" height="500" viewbox="0 0 500 500" @mouseup="dEnd"><line x1="100" y1="100" x2="400" y2="100" stroke-width="10" stroke="#FF00FF" @mousedown.self.stop="mDownLine" @mousemove.self.stop="mMoveLine"/>
</svg>
</template>
<script>
export default {
data () {
return {
x: 0,
y: 0,
cx: 0,
cy: 0,xl: 0,
yl:0,
r: 0,
is_dragging: false,
},
methods: {mDownLine () {
this.is_dragging = true
this.x = event.pageX
this.y = event.pageY
this.cx = parseInt(event.target.attributes.x1.value)
this.cy = parseInt(event.target.attributes.y1.value)
this.xl = parseInt(event.target.attributes.x2.value) - parseInt(event.target.attributes.x1.value)
this.yl = parseInt(event.target.attributes.y2.value) - parseInt(event.target.attributes.y1.value)
},
mMoveLine () {
if (this.is_dragging && event.pageX !== 0 && event.pageY !== 0) {
console.log("move Line")
event.target.setAttribute('x1', event.pageX - this.x + this.cx)
event.target.setAttribute('y1', event.pageY - this.y + this.cy)
event.target.setAttribute('x2', event.pageX - this.x + this.cx + this.xl)
event.target.setAttribute('y2', event.pageY - this.y + this.cy + this.yl)
}
},dEnd () {
//マウスのドラッグ終了時、変数を初期値に戻しておきます
if (this.is_dragging) {
this.is_dragging = false
this.x = 0
this.y = 0
this.cx = 0
this.cy = 0this.xl = 0
this.yl = 0
}
}}
4. Polygon(多角形)
<template>
<svg id="artboard" xmlns="http://www.w3.org/2000/svg" style="background-color:#ccc" width="500" height="500" viewbox="0 0 500 500" @mouseup="dEnd">
<polygon points="20 30, 35 10, 50 30" stroke-width="1" stroke="#000000" fill="#FF00FF" @mousedown.self.stop="mDownPolygon" @mousemove.self.stop="mMovePolygon" />
<polygon points="60 30, 75 10, 90 30, 75 50" stroke-width="1" stroke="#000000" fill="#FF00FF" @mousedown.self.stop="mDownPolygon" @mousemove.self.stop="mMovePolygon" /></svg>
</template>
<script>
export default {
data () {
return {
x: 0,
y: 0,
cx: 0,
cy: 0,xl: 0,
yl:0,
r: 0,arr: '0 0, 0 0, 0 0',
is_dragging: false,
},
methods: {,
mDownPolygon () {
this.is_dragging = true
this.x = event.pageX
this.y = event.pageY
this.arr = event.target.attributes.points.value
},
mMovePolygon () {
if (this.is_dragging && event.pageX !== 0 && event.pageY !== 0) {
let points = ''
const difX = event.pageX - this.x
const difY = event.pageY - this.y
this.arr.split(', ').forEach(function( value ) {
const xy = value.split(' ')
const x1 = difX + parseInt(xy[0])
const y1 = difY + parseInt(xy[1])
if (points === ''){
points = x1 + ' ' + y1
} else {
points += ', ' + x1 + ' ' + y1
}
})
event.target.setAttribute('points', points)
}
},dEnd () {
//マウスのドラッグ終了時、変数を初期値に戻しておきます
if (this.is_dragging) {
this.is_dragging = false
this.x = 0
this.y = 0
this.cx = 0
this.cy = 0this.xl = 0
this.yl = 0
this.arr = '0 0, 0 0, 0 0'
}
}}
5. Image(埋め込んだ画像) /static内のfavicon.icoを使用します
<template>
<svg id="artboard" xmlns="http://www.w3.org/2000/svg" style="background-color:#ccc" width="500" height="500" viewbox="0 0 500 500" @mouseup="dEnd"><image xlink:href="/favicon.ico" x="300" y="300" width="50" height="40" @mousedown.self.stop="mDownSquare" @mousemove.self.stop="mMoveSquare" />
</svg>
</template>
<script>
export default {
data () {
return {
x: 0,
y: 0,
cx: 0,
cy: 0,
r: 0,
is_dragging: false,
},
methods: {mDownSquare () {
this.is_dragging = true
this.x = event.pageX
this.y = event.pageY
this.cx = parseInt(event.target.attributes.x.value)
this.cy = parseInt(event.target.attributes.y.value)
},
mMoveSquare () {
if (this.is_dragging && event.pageX !== 0 && event.pageY !== 0) {
event.target.setAttribute('x', event.pageX - this.x + this.cx)
event.target.setAttribute('y', event.pageY - this.y + this.cy)
}
},dEnd () {
//マウスのドラッグ終了時、変数を初期値に戻しておきます
if (this.is_dragging) {
this.is_dragging = false
this.x = 0
this.y = 0
this.cx = 0
this.cy = 0
}
}}
以上ですー!!
上記を組み合わせて、複数の図形を動かすこともできるので、遊んでみてください
今回初めてMacでgif画像を作ったのですが、下記の記事を参考にさせていただきました!簡単便利ーーー!
おやすみなさいーー
【AWS CLI】2つ以上のAWSアカウントを使い分ける
AWSのアカウントを2つ(仕事用&プライベート用)持つことになり、AWS CLIで使い分けはどうすれば?となったので、解決方法を紹介します。
1. まず、2つのアカウントそれぞれでIAMユーザを登録する
*IAMサービスの「Users」を選択
*「Add user」ボタンをクリック
* [User name]を記入、[Access Type]をProgrammatic access (AWS CLIでアクセスできる様にするため)にチェックを入れて、下の方にある[Add User]ボタンをクリック
*[Create group]ボタンをクリックし、[Group name]を記入し、与える権限を選択
(今回は、[Group name]をAdminという名前にし、全ての権限(Administrator Access)を与える設定にしました。)
*こんな風に表示されれば、権限を与える設定登録に成功![Next: Tags]をクリック
*Tags設定は必須ではないので、何も記載しないで、[Next:Review]をクリック
*Reveiw画面で、設定を確認し、OKなら[Create user]をクリック
*ユーザ作成が成功したら、下記のように表示されるので、[Access Key ID], [Secret access key]をメモしておいてください(後でAWS CLIの設定で使用します)
*他のAWSアカウントも、上記と同じ手順で、権限を与えられたIAMユーザを作成し、[Access Key ID], [Secret access key]をメモしておいてください
*curlコマンドで、AWS CLIのパッケージをローカルにダウンロード
curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
*インストール実行
(パスワードを聞かれた場合はPCにログインする時のユーザパスワード)
sudo installer -pkg AWSCLIV2.pkg -target /
*正しくインストールされたか確認
which aws
=> /usr/local/bin/aws が表示されればOK
aws --version
=> aws-cli/2.0.13 Python/3.7.4 Darwin/19.3.0 botocore/2.0.0dev17 のようにバージョンが表示されればOK
*コンソール上で下記コマンドをうつ
aws configure
*すると、下記4つの入力欄が表示されるのでそれぞれ入力(デフォルトのユーザとして登録したいAWSアカウントのIAM情報を入力)
AWS Access Key ID [None]: ここに、上記で確認したAccess Key ID入力
AWS Secret Access Key [None]:ここに、上記で確認したSecret Access Key入力
Default region name [None]: 契約している地域(ap-northeast-1など)
Default output format [None]: json
*次に、他のユーザを登録(名前付きユーザとして登録)するため、コンソール上で下記コマンドをうつ。(赤い部分を、登録したいユーザ情報に変更してください)
aws configure set region us-west-2 --profile tapitapi
*すると、下記4つの入力欄が表示されるのでそれぞれ入力
AWS Access Key ID [None]: ここに、上記で確認したAccess Key ID入力
AWS Secret Access Key [None]:ここに、上記で確認したSecret Access Key入力
Default region name [None]: 契約している地域(ap-northeast-1など)
Default output format [None]: json
*2つのユーザが登録できたか確認するため、下記コマンド実行
aws configure list-profiles
=>
default
tapitapi
上記実行し、defaultと2つ目のユーザの名前(今回はtapitapi)が表示されればOK
3. それぞれの環境に合わせてAWS CLIを実行できるか確認するため、S3 bucketを作成してみる
S3 bucketがすでに作成されている場合は、4.へ進んでください
*S3 bucketsサービスで[Create bucket]ボタンをクリック
*[Bucket name]を記入して[Next]をクリック。(Regionなど変更したい場合は、select boxで他の地域に変更可能)
*オプションを選択し、[Next]をクリック
今回はDefault encription(S3 bucket内に配置したファイルを自動で暗号化してくれる設定)のみ選択しました。
バージョン管理や、アクセスログを取りたい場合は、Versioning, Server access loggingなども選択するといいです
*パーミッション設定で、Block all public access (外部からのアクセスをブロック)を選択し、[Next]をクリック
bucket を作成した後、フォルダごとに公開設定ができるので、今回はとりあえず、全てブロックする設定にしました
*Review画面で設定を確認し、OKなら、[Create bucket]をクリック
*こんな感じで、Bucketが作成されればOK
*上記の手順で、複数のAWSアカウント上でもBucketを作成してみてください
4. aws S3 コマンドで、それぞれのAWSアカウントを使い分ける
*まず、デフォルトのAWSアカウントS3bucketのフォルダ構成を調べる
aws s3 ls
これでS3bucketのフォルダが表示されればOK
*名前つきAWSアカウントS3bucketのフォルダ構成を調べる
aws s3 ls --profile tapitapi
これでS3bucketのフォルダが表示されればOK
以上ですーーー!!
awsコマンドは、--profile パラメタを指定することで、2つ以上のAWSアカウントを使い分けることができることが分かりました
今後PythonなどでAWS CLIのコマンドを使用したプログラムを書くときは、--profileを意識した方がいいと思います(ユーザによって複数のアカウントを登録している場合があるため。)
追加で、AWS CLIのコマンドを使用したプログラムを書いたとき、--outputパラメタでもつまづいたので、参考までに記載しておきます
おやすみなさい
【Nuxt.js】サブディレクトリをBaseURLにする方法
Nuxt.js のgenerateコマンドで作成した静的ページを、phpで作ったサイトと共存させることになり、サブディレクトリ(今回はhttp://example.com/nuxt_dir/)内に配置する際にやったことを紹介します。
1. .envを使用できる様にする
詳細はこちらが参考になれば:
*dotenvモジュールをインストール
npmで管理してる場合
npm install @nuxtjs/dotenv
yarnで管理してる場合
yarn add @nuxtjs/dotenv
*nuxt.config.jsに設定を記載(赤文字部分を追加)
require('dotenv').config()
export default {
/* 略 */
buildModules: [
'@nuxtjs/dotenv'
],/* 略 */
}
* .envファイルを作成し、配置するサブディレクトリ(今回は/nuxt_dir/)用の定数を記載
BASE_URL = /nuxt_dir
2. nuxt.config.jsに赤文字部分を記載(linkやscriptでBaseUrl配下を参照するものにもprocess.env.BASE_URL を記載)
require('dotenv').config()
export default {
mode: "universal",
router: {
base: process.env.BASE_URL || "",
},
head: {
title: process.env.npm_package_name || "",
base: {
href: process.env.BASE_URL
},
link: [
{ rel: "icon", type: "image/x-icon", href: process.env.BASE_URL + "/favicon.ico" }
],
script: [{ src: process.env.BASE_URL + "/menu.js" }
],
}
ローカルで開発行う場合は、.env内のBASE_URL=''にしておくと、localhost:3000直下でページが表示されます。
3. npm run generateで静的ページを作成
npm run generate または yarn generate
上記コマンドで、/dist 内に静的ページが作成されます。試しに/dist/index.htmlを確認してみると、
<!doctype html>
<html data-n-head-ssr>
<head>
<title>Home</title>// 略
<link data-n-head="ssr" rel="icon" type="image/x-icon" href="/nuxt_dir/favicon.ico"><script data-n-head="ssr" src="/nuxt_dir/menu.js"></script>
<base href="/nuxt_dir/">
// 略
</head>
<body><a href="/nuxt_dir/page2">page2</a>
</body>
</html>
nuxt.config.jsで定義したheadタグ内部も、/nuxt_dir というサブディレクトリが記載されて生成され、
bodyタグ内部も/nuxt_dir というサブディレクトリが記載されて生成されていることがわかります。(aタグ部分は、pages/index.vueでは<nuxt-link to="/page2">page2</nuxt-link>と記載されています)
4. /dist内の静的ファイル全てを、サーバのサブディレクトリ内(今回の場合、http://example.comサーバの/nuxt_dirディレクトリ内)に配置
以上ですー!!
Nuxtはgenerateコマンドで、普通のhtmlとして使える静的ファイルを吐き出してくれるので、とっても便利!!
おやすみなさい