import本身是懶加載模式,但是使用時(shí)有限制必須放在第一行 ,import()可以在任意位置使用
案例
src/index.js (src/public.js 自行創(chuàng)建本章忽略)
//
window.btnclick = () =>{
import('./public').then((data)=>{
console.log('data == ', data.default);
})
}
document.write('<div onClick="window.btnclick()">點(diǎn)擊</div>')
webpack.config.js
// webpack是node寫出來(lái)的, 需要node的寫法
let path = require('path');
// html-webpack-plugins 插件
let HtmlWebpackPlugins = require('html-webpack-plugin');
// 抽離css為單獨(dú)文件
let MiniCssExtractPlugin = require('mini-css-extract-plugin');
// 導(dǎo)入樣式壓縮
let OptimizeCssPlugin = require('optimize-css-assets-webpack-plugin');
// 壓縮js
const TerserPlugin = require('terser-webpack-plugin')
// webpack相關(guān)配置
module.exports = {
// 壓縮 model 必須是production才有效果
optimization: {
minimizer: [
new TerserPlugin({}),
new OptimizeCssPlugin()
]
},
// 開發(fā)服務(wù)的配置
devServer: {
// 端口,默認(rèn)8080
port: '8099',
// 啟動(dòng)壓縮
//compress: true
},
// 模式,2種:生產(chǎn)模式(production)和開發(fā)模式(development)
// 開發(fā)模式不壓縮打包后代碼,生產(chǎn)模式壓縮打包后代碼
mode: 'production',
// 入口,表示從哪里開始打包
entry: './src/index.js',
// 表示出口(輸出后文件相關(guān)配置)
output: {
// 哈希8位
filename: 'main.[hash:8].js',
// 輸出后的路徑(必須是一個(gè)絕對(duì)路徑)
path: path.resolve(__dirname, '../dist')
},
// 插件配置
plugins: [
new HtmlWebpackPlugins({
// 模板位置
template: 'index.html',
// 文件名
filename: 'index.html'
}),
// 抽離css為單獨(dú)文件
new MiniCssExtractPlugin({
filename: 'css/main.css'
})
],
// 模塊處理
module: {
// loader
rules: [{
test: /\.html$/,
use: 'html-withimg-loader'
},
{
test: /\.(png|jpg|gif)$/,
use: {
loader: 'url-loader',
options: {
// 打包少于1000kb用base64,否則使用file-loader產(chǎn)生文件
limit: 1000,
// 產(chǎn)出路徑
outputPath: 'img/',
// 只給圖片添加前綴,如果使用publicPath,outputPath無(wú)效
// publicPath: 'http://itssh.cn/'
}
}
},
{
test: /\.js$/, //匹配js文件
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-env'
],
plugins: [
["@babel/plugin-proposal-decorators", {
"legacy": true
}],
["@babel/plugin-proposal-class-properties", {
"loose": true
}],
"@babel/plugin-transform-runtime"
]
}
}
},
{
test: /\.css$/, //匹配css文件
// css-load處理完 再 抽離,從后往前執(zhí)行l(wèi)oader
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
},
{
test: /\.less$/, //匹配less文件
// 從后向前執(zhí)行
use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'less-loader']
}
]
}
}