起因
嘗試將使用 webpack
進(jìn)行打包傳統(tǒng)頁(yè)面溉仑、jquery恢准。
解決方案
使用 cdn 方式
示例代碼
src目錄結(jié)構(gòu)
subpage.html
通過(guò)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>測(cè)試非 node 頁(yè)面打包</title>
</head>
<body>
父頁(yè)面
<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執(zhí)行");
$("#div_sub").load("subpage.html")
console.log("index.js執(zhí)行結(jié)束");
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' //模板地址
})
]
};
小結(jié)
打包時(shí)各html
均會(huì)自動(dòng)引入入口js
榄审,需注意后續(xù)文件是否存在重復(fù)引用及路徑問(wèn)題
重復(fù)引用
使用 IgnorePlugin 忽略本地文件方式
示例代碼
目錄結(jié)構(gòu)
subpage.html
通過(guò)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' //模板地址
})
],
//將外部變量或者模塊加載進(jìn)來(lái)
externals : {
'jquery' : 'window.jQuery'
}
};
小結(jié)
打包完目錄
打包完需將
StaticRes
拷貝至dist
目錄若河,檢查引用路徑