我有一个这样的webpack配置js:
entry: {
language: path.resolve(__dirname, 'src/scripts/lang.js'),
config: path.resolve(__dirname, 'src/scripts/config.js'),
mainFunctions: path.resolve(__dirname, 'src/scripts/utilFunctions.js'),
},
此脚本序列位于html文件的底部:
<script src="../plugins/jQuery/jquery-3.4.1.min.js"></script>
<script src="../plugins/Popper/popper.min.js"></script>
<script src="../plugins/Bootstrap/bootstrap.min.js"></script>
<script src="../plugins/Magnific/magnificPopup.min.js"></script>
</body>
</html>
因此,编译后HtmlWebpackPlugin
会生成以下结构:
<script src="../plugins/jQuery/jquery-3.4.1.min.js"></script>
<script src="../plugins/Popper/popper.min.js"></script>
<script src="../plugins/Bootstrap/bootstrap.min.js"></script>
<script src="../plugins/Magnific/magnificPopup.min.js"></script>
<script type="text/javascript" src=".././js/language-82d9013312d51ba09842.js"></script>
<script type="text/javascript" src=".././js/vendors~config-620ba3d9ae4472f968ab.js"></script>
<script type="text/javascript" src=".././js/config-28c647d3bd0894bac005.js"></script>
<script type="text/javascript" src=".././js/utilFunctions-1ae3ee4b074ef90d909b.js"></script>
</body>
</html>
问题是如何为每个html文件包含自己的js脚本,最终结果应该是这样。
在index.html
// ----- connected scripts in here -------- //
<script type="text/javascript" src=".././js/utilFunctions-1ae3ee4b074ef90d909b.js"></script>
<script type="text/javascript" src=".././js/index.js"></script>
</body>
在home.html
// ----- connected scripts in here -------- //
<script type="text/javascript" src=".././js/utilFunctions-1ae3ee4b074ef90d909b.js"></script>
<script type="text/javascript" src=".././js/home.js"></script>
</body>
我无法在utilFunctions
对象(在entry
内的webpack.config.js
之后添加到,那么包含的部分将出现在每个html文件中。
我也不能添加html文件,因为顺序应该是这样的:首先是插件,然后是我自己的函数。 请帮助我卡住。
答案 0 :(得分:1)
您可以控制webpack导入文件和手动导入特定文件的顺序
<% if(htmlWebpackPlugin.files.chunks.body) { %>
<script src="<%= htmlWebpackPlugin.files.chunks.body.entry %>"></script>
<% } %>
<script src="home.js"></script>
中找到该示例
答案 1 :(得分:0)
我这样解决:
entry: {
language: path.resolve(__dirname, 'src/scripts/lang.js'),
config: path.resolve(__dirname, 'src/scripts/conf.js'),
mainFunctions: path.resolve(__dirname, 'src/scripts/utilFunctions.js'),
index: path.resolve(__dirname, 'src/scripts/index.js'),
home: path.resolve(__dirname, 'src/scripts/home.js'),
},
向条目index
和home
添加了另外两个块
然后在 htmlWebpackPlugin 中这样写:
['index', 'home'].forEach((file) => {
webpackConfig.plugins.push(
new HtmlWebpackPlugin({
filename: `./html/${file}.html`,
template: `./src/html/${file}.html`,
chunks:['language','config','mainFunctions', file],
minify: {
removeComments: true,
// collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
},
})
);
})