起因
尝试将使用 webpack
进行打包传统页面、jquery。
解决方案
使用 cdn 方式
示例代码
subpage.html
通过load
方式加载到index.html
# index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试非 node 页面打包</title>
</head>
<body>
父页面
<div id="div_sub"></div>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript/index.js"></script>
</body>
</html>
# index.js
console.log("index.js执行");
$("#div_sub").load("subpage.html")
console.log("index.js执行结束");
webpack打包
# 版本 webpack 4.29.6
# 初始化
cnpm init -y
cnpm install webpack webpack-cli --save-dev
cnpm install clean-webpack-plugin --save-dev
cnpm install --save-dev html-webpack-plugin
http-server
# webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: './src/javascript/index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
hash: true,
template: './src/index.html' //模板地址
}),
new HtmlWebpackPlugin({
filename: 'subpage.html',
hash: true,
template: './src/subpage.html' //模板地址
})
]
};
小结
打包时各html
均会自动引入入口js
,需注意后续文件是否存在重复引用及路径问题
使用 IgnorePlugin 忽略本地文件方式
示例代码
subpage.html
通过load
方式加载到index.html
,StaticRes
为需要忽略的文件
webpack打包
# 版本 webpack 4.29.6
# 初始化
cnpm init -y
cnpm install webpack webpack-cli --save-dev
cnpm install clean-webpack-plugin --save-dev
cnpm install --save-dev html-webpack-plugin
cnpm install uglifyjs-webpack-plugin --save-dev
http-server
# webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack");
var ignorePlugin = new webpack.IgnorePlugin(/\.\/src\/jquery.js/);
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
entry: {
index: './src/javascript/index.js'
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
libraryTarget: 'var'
},
optimization: {
minimizer: [
new UglifyJsPlugin({
uglifyOptions: {
warnings: false,
parse: {},
compress: {},
mangle: true, // Note `mangle.properties` is `false` by default.
output: null,
toplevel: false,
nameCache: null,
ie8: false,
keep_fnames: false,
},
}),
],
},
plugins: [
ignorePlugin,
new HtmlWebpackPlugin({
filename: 'index.html',
hash: true,
template: './src/index.html' //模板地址
}),
new HtmlWebpackPlugin({
filename: 'subpage.html',
hash: true,
template: './src/subpage.html' //模板地址
})
],
//将外部变量或者模块加载进来
externals : {
'jquery' : 'window.jQuery'
}
};
小结
打包完需将
StaticRes
拷贝至dist
目录,检查引用路径