質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Pug

Pug(旧Jade)とは、HTMLを書くためのテンプレートエンジン。タグで囲む必要がないなど記述を省略できるため、HTMLの記述が簡単になります。ファイル分割も可能で、変数やループなど便利な機能も備わっています。

Q&A

解決済

1回答

1954閲覧

WebpackのPugで別ファイルの関数を呼び出したい

umesister

総合スコア0

Pug

Pug(旧Jade)とは、HTMLを書くためのテンプレートエンジン。タグで囲む必要がないなど記述を省略できるため、HTMLの記述が簡単になります。ファイル分割も可能で、変数やループなど便利な機能も備わっています。

0グッド

0クリップ

投稿2021/10/19 09:07

前提・実現したいこと

webpack5環境にて別ファイルで定義しているPugファイル内の「関数」を呼び出したいです。

発生している問題・エラーメッセージ

関数が呼び出せません。
index.pugというファイルで別ファイル(_function.pug)で定義している関数(is_page)を呼び出すと以下のようなエラーが表示されます。

Html Webpack Plugin: ReferenceError: is_page is not defined - index.pug:22 template webpack_sample_v1_pug3/src/pug/index.pug:22:1 - index.js:450 [webpack_sample_v1_pug3]/[html-webpack-plugin]/index.js:450:16 - task_queues.js:97 processTicksAndRejections internal/process/task_queues.js:97:5 - async Promise.all

ディレクトリ構造

webpack_sample_v1_pug3 ├ package.json ├ package-lock.json ├ webpack.config.js ├ node_modules └ src └ js └ pug └ _function.pug └ index.pug └ dist └ js

該当のソースコード

Pugファイル

_function.pug(関数を宣言)

pug

1- 2 /** 3 * ページ判別 4 */ 5 6 function has_class( name ) { 7 /** 8 * Return true if the class is assigned to <body>. 9 * ex: if has_class( 'classname' ) 10 */ 11 return page.bodyclass.indexOf( name ) != -1; 12 } 13 14 function is_page( name ) { 15 /** 16 * Return true if the class is assigned to <body>. 17 * ex: if is_page( 'classname' ) 18 */ 19 return has_class( name ); 20 }
index.pug(関数を呼び出す)

is_page('hoge')でpage.bodyclassがhogeだったらという簡単なif文です。

pug

1include /_function 2 3- page = {}; 4block vars 5 - page.title = 'テスト'; 6 - page.description = site.description; 7 - page.keywords = site.keywords; 8 - page.bodyclass = 'hoge'; 9 10doctype html 11html(lang="jp") 12 head 13 meta(charset="UTF-8") 14 meta(http-equiv="X-UA-Compatible", content="IE=edge") 15 meta(name="viewport", content="width=device-width, initial-scale=1.0") 16 link(href='./css/style.min.css',rel='stylesheet',type='text/css') 17 title テスト 18 body 19 .wrap 20 if is_page('hoge') //ここでエラーが起きています。 21 p hogeページ 22 else 23 p hogeページではないです 24 25 script(src="./js/bundle.js")

webpack.config.js

javascript

1// webpack.config.js 2 3const path = require("path"); 4const MODE = "development"; 5 6const enabledSourceMap = MODE === "development"; 7 8const MiniCssExtractPlugin = require("mini-css-extract-plugin"); 9const CopyPlugin = require("copy-webpack-plugin"); 10 11const globule = require("globule"); 12const webpack = require('webpack'); 13 14const app = { 15 mode: MODE, 16 entry: ['./src/js/index.js'], 17 output: { 18 path: path.resolve(__dirname, "dist"), 19 filename: "./js/bundle.js", 20 }, 21 devtool: "source-map", 22 module: { 23 rules: [ 24 { 25 test: /.js$/, 26 use: [ 27 { 28 loader: "babel-loader", 29 options: { 30 presets: [ 31 "@babel/preset-env", 32 ], 33 }, 34 }, 35 ], 36 }, 37 { 38 test: /.scss/, // 対象となるファイルの拡張子 39 use: [ 40 { 41 loader: MiniCssExtractPlugin.loader, 42 }, 43 { 44 loader: "css-loader", 45 options: { 46 url: false, 47 sourceMap: enabledSourceMap, 48 49 importLoaders: 2, 50 }, 51 }, 52 { 53 loader: "postcss-loader", 54 options: { 55 postcssOptions: { 56 plugins: [ 57 ["autoprefixer", { grid: true }], 58 ], 59 }, 60 }, 61 }, 62 { 63 loader: "sass-loader", 64 options: { 65 sourceMap: enabledSourceMap, 66 }, 67 }, 68 ], 69 }, 70 { 71 test: /.pug$/, 72 use: [ 73 { 74 loader: "pug-loader", 75 options: { 76 pretty: true, 77 globals: ["page"], 78 self: true, 79 root: path.resolve(__dirname, 'src/pug') 80 } 81 } 82 ] 83 } 84 ], 85 }, 86 devServer: { 87 static: { 88 watch: true, 89 directory: `${__dirname}/src`, 90 }, 91 open: true 92 }, 93 plugins: [ 94 new MiniCssExtractPlugin({ 95 filename: "./css/style.min.css", 96 }), 97 new CopyPlugin({ 98 patterns: [{ 99 from: `${path.resolve(__dirname, "src")}/img/`, 100 to: `${path.resolve(__dirname, "dist")}/img/` 101 }], 102 }), 103 new webpack.ProvidePlugin({ 104 $: 'jquery' 105 }) 106 ], 107 target: ["web",'es5'], 108 devtool: "source-map", 109 watchOptions: { 110 ignored: /node_modules/ //正規表現で指定 111 } 112}; 113 114//srcフォルダからpngを探す 115const templates = globule.find("./src/pug/**/*.pug", { 116 ignore: [ 117 "./src/pug/**/_*.pug", 118 ] 119}); 120 121//pugファイルがある分だけhtmlに変換する 122templates.forEach((template) => { 123 const fileName = template.replace("./src/pug/", "").replace(".pug", ".html"); 124 app.plugins.push( 125 new HtmlWebpackPlugin({ 126 filename: `${fileName}`, 127 template: template, 128 inject: false, //false, head, body, trueから選べる 129 minify: false //本番環境でも圧縮しない 130 }) 131 ); 132}); 133 134module.exports = app;

package.json

json

1{ 2 "scripts": { 3 "build": "webpack --mode production", 4 "dev": "webpack --mode development", 5 "watch": "webpack --mode development --watch", 6 "start": "webpack serve --mode development" 7 }, 8 "devDependencies": { 9 "@babel/core": "^7.15.5", 10 "@babel/preset-env": "^7.15.6", 11 "autoprefixer": "^10.3.7", 12 "babel-loader": "^8.2.2", 13 "copy-webpack-plugin": "^9.0.1", 14 "css-loader": "^6.2.0", 15 "globule": "^1.3.3", 16 "html-loader": "^2.1.2", 17 "html-webpack-plugin": "^5.3.2", 18 "html-webpack-pug-plugin": "^3.0.0", 19 "mini-css-extract-plugin": "^2.3.0", 20 "path": "^0.12.7", 21 "postcss": "^8.3.9", 22 "postcss-loader": "^6.1.1", 23 "pug": "^2.0.4", 24 "pug-html-loader": "^1.1.5", 25 "pug-loader": "^2.4.0", 26 "sass": "^1.39.2", 27 "sass-loader": "^12.1.0", 28 "style-loader": "^3.2.1", 29 "webpack": "^5.52.1", 30 "webpack-cli": "^4.8.0", 31 "webpack-dev-server": "^4.2.0" 32 }, 33 "dependencies": { 34 "jquery": "^3.6.0" 35 }, 36 "browserslist": [ 37 "> 3% in JP", 38 "ie 11", 39 "android 4.4", 40 "last 1 versions" 41 ] 42}

試したこと

index.pug内で_function.pug内の関数をまるっとコピペしてみると期待通りの関数が呼び出せます。

- /** * ページ判別 */ function has_class( name ) { /** * Return true if the class is assigned to <body>. * ex: if has_class( 'classname' ) */ return page.bodyclass.indexOf( name ) != -1; } function is_page( name ) { /** * Return true if the class is assigned to <body>. * ex: if is_page( 'classname' ) */ return has_class( name ); } - page = {}; block vars - page.title = 'テスト'; - page.description = site.description; - page.keywords = site.keywords; - page.bodyclass = 'hoge'; doctype html html(lang="jp") head meta(charset="UTF-8") meta(http-equiv="X-UA-Compatible", content="IE=edge") meta(name="viewport", content="width=device-width, initial-scale=1.0") link(href='./css/style.min.css',rel='stylesheet',type='text/css') title テスト body .wrap if is_page('hoge') p hogeページ else p hogeページではないです script(src="./js/bundle.js")

推測

別ファイルなのでスコープが閉じられている可能性が高いです。
別ファイルの変数はwebpack.config.jsのpug-loader→globalsで変数を定義しているので、サイト全体で使えます。

どうかご教授の方よろしくお願い致します...!!

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

変数に関数を代入してwebpack.config.jsで定義すると渡せました。

投稿2021/10/22 10:50

umesister

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問