想象一下,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";
(...)
我安装了webpack,将每个入口点作为每个文件名。现在,将普通的js文件(例如`./nav.js)包含到每个文件中的方式是什么?
entry: {
home: "./resources/js/sections/home.js",
settings: "./resources/js/sections/settings.js",
(...)
}
(...)
output: {
filename: '[name].js',
}
//选项A
在每个子页面(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"
}
答案 0 :(得分:1)
您可以使用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']
}),
]
}