Answer the question
In order to leave comments, you need to log in
Can Webpack be configured to selectively include scripts?
I have a simple framework for managing html forms. And you need to initialize the classes of this framework differently on different pages. That is, I would like the JS code of the framework to get into the bundle during assembly (standard webpack behavior), and the instantiating scripts would be connected to the pages as separate files (or code fragments). The main thing is that these scripts should have a common namespace after minification.
I have been struggling with this problem for the third day, but I did not find a good solution. Therefore, I will be grateful for any help.
I found the HtmlWebpackTagsPlugin plugin, which complements the functionality of the HtmlWebpackPlugin and stupidly adds links to files with JS scripts.
I need something similar, but instead of a set of links, specify the names of the files. Webpack would load these files as modules, run them through Babel and inject them into the necessary files. That is, the config might look something like this:
new HtmlWebpackScriptInjectPlugin({
// Файл со скриптом для конкретной страницы
filesWithScripts: ['../scripts/scriptForMainPage'],
append: true,
// Название файла, в который нужно вставить ссылку на скрипт
destinationFiles: ['./views/main_page.njk']
})
]
Answer the question
In order to leave comments, you need to log in
It seems that he was able to solve his problem using the html-webpack-injector plugin and setting up the chunks. Code example:
const testArr2 = [
new HtmlWebpackPlugin({
template: `./templates/pages/test.ejs`,
filename: `./views/test.njk`,
chunks: ['index', 'chunk1']
}),
new HtmlWebpackInjector(),
new HtmlWebpackPlugin({
template: `./templates/pages/test2.ejs`,
filename: `./views/test2.njk`,
chunks: ['index', 'chunk2']
}),
new HtmlWebpackInjector()
]
export default {
context: path.resolve(__dirname, 'source'),
entry: {
index: './entry.js',
chunk1: './templates/pages/chunk1.js',
chunk2: './templates/pages/chunk2.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'public'),
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: 'style.css'
}),
...testArr2
< some code >
{
test: /\.m?js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
minified: false
}
}
},
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question