注意:本文章假设你已经阅读了【Webpack:安装和初始化项目(1)】
打包文件的配置
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"private": true, //添加此代码,私有的部署防止意外发布为公开
"main": "index.js",//删除此行代码,去掉入口
"scripts": {
//自定义打包命令,可以在项目路径使用 npm run boundle进行打包。
//不用自定义命令,可以在项目路径使用 npx webapck进行打包
"boundle": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^4.0.1",
"webpack-cli": "^2.0.9"
},
"dependencies": {}
}
webapck.config.json
const path = require('path');//node的核心模块
module.exports = {
//mode为打包的模式,默认是production会压缩代码,平常用development
mode: 'development',
entry: './src/index.js', //打包的入口文件,chunk Name是:main
output: {
filename: 'main.js', //合并模块js文件后的包名
path: path.resolve(__dirname, 'dist') //打包后文件输出的路径
}};
打包的文件
src下的index.js
var Header = require('./header.js');
var Sidebar = require('./sidebar.js');
var Content = require('./content.js');
new Header();
new Sidebar();
new Content();
三个被index.js引用的js文件
//content.js文件
function Content() {
var dom = document.getElementById('root');
var content = document.createElement('div');
content.innerText = 'content';
dom.append(content);
}
module.exports = Content;
//header.js文件
function Header() {
var dom = document.getElementById('root');
var header = document.createElement('div');
header.innerText = 'header';
dom.append(header);
}
module.exports = Header;
//sidebar.js文件
function sidebar() {
var dom = document.getElementById('root');
var sidebar = document.createElement('div');
sidebar.innerText = 'sidebar';
dom.append(sidebar);
}
module.exports = sidebar;
html引用打包后的js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>我是網頁內容</h1>
<div id='root'></div>
</body>
<script src="../dist/main.js"></script>
</html>