Как правильно настроить конфигурацию веб-пакета для включения общих блоков, используемых в многостраничном (и входном) приложении? - PullRequest
0 голосов
/ 18 января 2019

Представьте, что у вас ниже структура html файлов:

./home.html
./settings.html
./contact.html

Также есть файлы ниже js

./nav.js <-- common - used in all html files
./home.js <-- used only in home.html, below follow the same rule
./settings.js
./contact.js

И некоторые модули из node_modules:

"jquery" "moment"

, которые импортируются, как если бы это было необходимо:

./home.js
import $ from "jquery";
(...)

У меня есть настроенный веб-пакет для каждой точки входа в качестве имени каждого файла.Теперь, как можно было бы включить в каждый файл обычные js-файлы, такие как `./nav.js?

entry: {
  home: "./resources/js/sections/home.js",
  settings: "./resources/js/sections/settings.js",
  (...)
} 
(...)
output: {
  filename: '[name].js',
}

// Опция A

Импортировать raw nav.js, как другоймодуль на каждой подстранице (home.js, contact.js, settings.js)

import nav from ./nav.js
nav();

// Опция B

создать еще одну запись для ./nav.js и вручную добавить в комплекте nav.jsк каждому html наряду с другими связанными файлами.

entry: {
  (...)
  nav: "./resources/js/sections/nav.js"
}

1 Ответ

0 голосов
/ 18 января 2019

Вы можете использовать HtmlWebPackPlugin , чтобы динамически добавлять скрипты к вашим HTML-страницам.

Прежде всего установите плагин:

npm install html-loader html-webpack-plugin --save-dev

Затем используйте конфигурацию:

const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = {
  entry: {
    nav: './resources/js/sections/nav.js',
    home: './resources/js/sections/home.js',
    settings: './resources/js/sections/settings.js',
    contact: './resources/js/sections/contact.js',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'), // folder where all tranformed files will be placed
  },
  rules: [
    {
      test: /\.html$/,
      use: [{ 
        loader: "html-loader", 
        options: { minimize: true } 
      }]
    }
  ],
  plugins: [
    // create an instance of HtmlWebPackPlugin for every page of a multipage website
    new HtmlWebPackPlugin({
      template: "./resources/html/home.html", // take html from this path
      filename: "./home.html", // name it 'home.html' and insert to the root of output folder
      chunks: ['nav', 'home'] // insert dymamically nav.js and home.js to home.html
    }),
    new HtmlWebPackPlugin({
      template: "./resources/html/settings.html",
      filename: "./settings.html",
      chunks: ['nav', 'settings']
    }),
    new HtmlWebPackPlugin({
      template: "./resources/html/contact.html",
      filename: "./contact.html",
      chunks: ['nav', 'contact']
    }),
  ]
}
...