以windows系统打包为例
下载node-v8.11.3-x64.msi安装
https://nodejs.org/dist/v8.11.3/node-v8.11.3-x64.msi
选定一个目录,比如D:\simple_webpack,切换到该目录,并创建app和build
>> d:
>> cd d:/simple_webpack
>> mkdir app
>> mkdir build
component.js文件内容如下:
export default (text="default value") => {
const element = document.createElement("div");
const h1 = document.createElement("h1");
h1.innerHTML = text;
element.appendChild(h1);
return element;
}
index.js文件内容如下:
import component from "./component";
document.body.appendChild(component());
将component.js和index.js放在app目录下
编写webpack.config.js文件内容如下:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const PATHS = {
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build'),
};
module.exports = {
entry:{
app: PATHS.app,
},
output:{
path: PATHS.build,
filename: '[name].js',
},
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
}
]
},
plugins:[
new HtmlWebpackPlugin({
titile: 'webpack demo',
}),
],
mode: 'development'
};
.babelrc文件内容如下:
{
"presets": ["es2015"],
"plugins": []
}
.babelrc和webpack.config.js文件放在当前目录,即D:\simple_webpack目录
执行npm相关命令
// 初始化,停顿地方直接Enter
>> npm init
// 安装webpack webpack-cli
>> npm install webpack --save-dev
>> npm install webpack-cli --save-dev
// 安装html_webpack-plugin插件
>> npm install html_webpack_plugin --save-dev
// 安装babel
>> npm install babel-core --save-dev
>> npm install babel-loader --save-dev
>> npm install babel-preset-es2015 --save-dev
执行命令
>> node_modules\.bin\webpack
在build目录中找到生成的index.html文件,并选择浏览器打开
随着操作系统升级,或者node,npm,webpack,plugin,loader版本更新,打包会产生些变化,本文只做参考。如有疑问可以一起探讨
webpack中文文档
https://www.webpackjs.com/concepts/