功能:
点击按钮1加载A.js,点击按钮2加载B.js。
目录:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<button id="Btn1">按钮1</button>
<button id="Btn2">按钮2</button>
</body>
</html>
main.js:
import Vue from 'vue';
// 点击按钮1再加载A.js 异步加载
document.getElementById('Btn1').onclick = function () {
require.ensure([], function () {
var A = require('./A.js');
console.log(A.data);
});
}
// 点击按钮2再加载B.js 异步加载
document.getElementById('Btn2').onclick = function () {
require.ensure([], function () {
var B = require('./B.js');
console.log(B.data);
});
}
A.js:
var A = {
data: '数据A'
};
//Node commonJs模块规范
module.exports = A;
B.js:
var B = {
data: '数据B'
};
//Node commonJs模块规范
module.exports = B;
webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const packagejson = require('./package.json');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
'main': './src/main.js',
// dependencies
'util': Object.keys(packagejson.dependencies)
},
output: {
path: path.resolve('./dist'),
filename: '[name].js'
},
watch: true,
plugins: [
new webpack.optimize.CommonsChunkPlugin({
// 第三方公共组件
name: 'common',
filename:'[name].js'
}),
new HtmlWebpackPlugin({
// chunks用于多入口文件,编译后的index.html中有多个script标签引入js,chunks数组中的顺序就是js引入的先后顺序
// common要放在前面
chunks: ['common', 'util', 'main'],
template: './src/index.html', // 参照物
inject: true // 注入js 默认值true 四个值:true false(一般不用) head body
})
]
}
package.json:
{
"name": "03es6",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack-dev-server --open --hot --inline",
"dev": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"css-loader": "^0.28.11",
"html-webpack-plugin": "^2.24.1",
"style-loader": "^0.23.1",
"vue": "^2.6.14",
"vue-loader": "^14.1.1",
"vue-template-compiler": "^2.5.17",
"webpack": "^3.12.0",
"webpack-dev-server": "^2.10.0"
},
"dependencies": {
"vue": "^2.6.14"
}
}
实现效果: