I have the following directory structure...
root
│ package.json
│ webpack-client.config.js
│ webpack-server.config.js
│ yarn.lock
├───assets
│ └───js
│ index.js
├───dist
│ │ header.html
│ │ hotel-details.html
│ │ hotel-list.html
│ │ index.html
│ │ server.js
│ │
│ └───static
│ └───j
│ index.js
├───node_modules
│ └...
├───server
│ database.js
│ index.js
└───views
header.html
hotel-details.html
hotel-list.html
index.html
I want to use Webpack for two things. 1. minify and bundle server side JS - export the bundle to dist/server.js
using server/index.js
as the entry point - I have achieved this using the webpack-server.config.js
provided below 2. minify each views/*.html
file and export it to dist/v/*.html
. If the html
files have tags I want to create minified bundles from those files and export them to dist/static/j/[html_filename].js
. - I'm struggling with this one. I managed to minify the .html
file and export it's .js
files to dist/static/j/[html_filename].js
. However, I can't use the .js
file from html as it uses syntax like require
or import
. I've provided the content of both assets/js/index.js
and dist/static/j/index.js
.
webpack-client.config.js
var path = require("path");
var fs = require("fs");
var htmlFiles = {};
fs.readdirSync(path.join(__dirname, 'views'))
.filter(f => (path.parse(f).ext.toLowerCase() === '.html'))
.forEach(f => {
var name = path.parse(f).name;
htmlFiles[name] = path.join(__dirname, 'views', f);
});
module.exports = {
module: {
rules: [
{
test: /\.html$/,
use: [
{ loader: 'file-loader', options: { name: '[name].[ext]', emitFile: true }},
{ loader: 'extract-loader' },
{
loader: 'html-loader',
options: {
minimize: true,
attrs: ['script:src']
}
},
]
},
{
test: /\.js$/,
use: [
{
loader: 'file-loader',
options: {
name: 'static/j/[name].[ext]',
publicPath: (p) => p.replace('static/', '')
}
},
{
loader: 'babel-loader',
options: {
presets: [
[
"babel-preset-env", {
"targets": {
"chrome": 52
}
}
]
]
}
},
]
}
]
},
target: 'web',
watch: true,
entry: htmlFiles,
output: {
path: path.join(__dirname, "dist"),
filename: '[name].html.js'
}
};
webpack-server.config.js
var path = require("path");
var fs = require("fs");
const MinifyPlugin = require('babel-minify-webpack-plugin');
var nodeLibs = {};
fs.readdirSync(path.join(__dirname, 'node_modules'))
.filter(x => x !== '.bin')
.forEach(mod => { nodeLibs[mod] = 'commonjs ' + mod; });
module.exports = {
externals: nodeLibs,
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['babel-preset-env']
}
}
}
]
},
plugins: [
new MinifyPlugin()
],
context: __dirname,
entry: {
server: "./server/index.js"
},
target: "node",
output: {
path: path.join(__dirname, "dist"),
filename: "server.js"
}
};
assets/js/index.js
import $ from '../../node_modules/jquery';
let scrollEnabled = true;
window.setScrollEnabled = (scrollEnabled) => {
$('body').css({backgroundColor: 'red'});
console.log('isScrollEnabled:', scrollEnabled);
}
Aucun commentaire:
Enregistrer un commentaire