Webpack 만 사용하여 기본 웹 사이트를 만들려고합니다. 내 목적은 example.com/about, example.com/contact와 같은 간단한 URL 구조를 갖는 것입니다.
Webpack에서는 HTMLWebpackPlugin을 사용할 수 있지만 모든 경로에 대한 인스턴스를 만들어야합니다. 그래서, 제 질문은 : 이것을 단순화하는 방법이 있습니까?
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/main.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
port: 5000,
},
plugins: [
new htmlWebpackPlugin({
title: 'Home',
filename: 'index.html',
template: './src/pages/home/index.html',
}),
new htmlWebpackPlugin({
title: 'About',
filename: 'about/index.html',
template: './src/pages/about/index.html',
}),
],
};
Webpack 구성 파일은 javascript입니다. 따라서 프로세스를 추상화하기 위해 몇 가지 도우미 함수를 추가하고 원하는 효과를내는 페이지 배열을 연결하면됩니다.
const htmlWebpackPlugin = require('html-webpack-plugin');
const generateHtmlPlugin = (title) => {
return new htmlWebpackPlugin({
title,
filename: 'index.html',
template: `./src/pages/${title.toLowerCase()}/index.html`,
});
}
const populateHtmlPlugins = (pagesArray) => {
res = [];
pagesArray.forEach(page => {
res.push(generateHtmlPlugin(page));
})
return res;
}
따라서 이것은 너무 많은 코드가 아니며 웹팩을 설정할 때 원하는 페이지 배열을 삽입 할 수 있습니다.
const pages = populateHtmlPlugins(["About", "Articles", "Users", "Contact"]);
module.exports = {
//...
plugins: pages
}
더 좋은 방법은 utils
폴더를 만들고 코드를 내 보낸 두 개의 모듈로 리팩터링 한 다음 populateHtmlPlugins()
웹팩 구성 파일로 가져 와서 매우 깔끔하게 유지할 수 있다는 것입니다.
이제 원하는만큼의 페이지를 쉽게 만들 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다