模块全部下载保存下来,方便教程创建demo3
npm init -y
npm -y install webpack webpack-cli --save-dev
npm install --save lodash
npm install -y style-loader css-loader file-loader csv-loader xml-loader
初始化配置
webpack.config.js
const path = require('path');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
修改了入口和输出文件
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./print.bundle.js"></script>
</head>
<body>
<script src="./app.bundle.js"></script>
</body>
</html>
src/print.js
export default function printMe() {
console.log('我是空气小白');
}
src/index.js
import _ from 'lodash';
import printMe from './print.js';
function component() {
var element = document.createElement('div');
var btn = document.createElement('button');
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
btn.innerHTML = '点我就进入了小白说明';
btn.onclick = printMe;
element.appendChild(btn);
return element;
}
document.body.appendChild(component());
image.png
html插件
HtmlWebpackPlugin
npm install --save-dev html-webpack-plugin
配置
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
plugins: [
new HtmlWebpackPlugin({
title: '首页'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
删除/dist/下的文件
执行
npm run build看看
,这个是他们自己自动创建了。
清理文件,可能存在旧的垃圾,所以需要删除,人工删除就选的笨拙了
npm install clean-webpack-plugin --save-dev
官方文档没有更新的哦,这个引入方法改了
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports = {
entry: {
app: './src/index.js',
print: './src/print.js'
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: '首页'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
现在往/dist下建立一个文件a.txt
运行npm run build,你会发现a.txt被删除了。
网友评论