我有以下目录结构...
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
我想将Webpack用于两件事。
缩小并捆绑服务器端JS - 使用dist/server.js
作为入口点将捆绑包导出到server/index.js
。我使用下面提供的webpack-server.config.js
来实现这一目标。
缩小每个views/*.html
文件并将其导出到dist/v/*.html
。如果html
文件包含<script>
个代码,我想从这些文件中创建缩小的捆绑包并将其导出到dist/static/j/[html_filename].js
。
.html
文件并将其.js
文件导出到dist/static/j/[html_filename].js
。但是,我无法使用html中的.js
文件,因为它使用require
或import
等语法。我提供了assets/js/index.js
和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);
}