npm install -g webpack webpack-cli
webpack -v //确认安装成功
webpack main.js -o all.js //手动打包js文件
1.从main.js出发,顺着import链寻找每个js文件
2.将每一个js文件智能打包,如果一个export暴露的函数没调用,就不会被打包
3.去import,export化,all.js兼容IE8
webpack.config.js //主文件
package.json //依赖文件
https://www.webpackjs.com/configuration/ //配置
自动打包配置 例子:
const path = require('path');
module.exports = {
entry: "./app/main.js", //入口文件
output: { //出口文件
// webpack 如何输出结果的相关选项
path: path.resolve(__dirname, "dist"), // string
// 所有输出文件的目标路径
// 必须是绝对路径(使用 Node.js 的 path 模块)
filename: "bundle.js", // string
},
mode: "production",
watch:true
}
webpack服务器
npm install -g webpack-dev-server //webpack 虚拟打包环境
起项目: webpack-dev-server --content-base ./www --port 8080
或者在 package.json 中
"scripts": {
"dev":"webpack-dev-server --content-base ./www --port 8080"
},
然后可以在CMD中 npm run dev
高级应用 解构:
依赖
{
"name": "test",
"version": "1.0.0",
"main": "webpack.config.js",
"scripts": {
"dev":"webpack-dev-server --content-base ./www --port 8080"
},
"author": "",
"License": "ISC",
"devDependencies": {
"babel-core": "^6.26.0",
"babel-preset-env": "^1.6.1"
},
"dependencies": {
"babel-loader": "^7.1.5",
"babel-preset-react": "^6.24.1",
"cnpm": "^6.1.0",
"react": "^16.10.2",
"react-dom": "^16.10.2"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"license": "ISC",
"description": ""
}
配置:webpack.config.js
const path = require('path');
module.exports = {
entry: "./www/app/main.js", //入口文件
output: { //出口文件
// webpack 如何输出结果的相关选项
path: path.resolve(__dirname, "www/dist"), // string
// 所有输出文件的目标路径
// 必须是绝对路径(使用 Node.js 的 path 模块)
filename: "bundle.js", // string
publicPath:"/xuni"
},
mode: "development",
watch:true,
module: {
// 关于模块配置
rules: [
// 模块规则(配置 loader、解析器等选项)
{
test: /\.jsx?$/,
include: [
path.resolve(__dirname, "www/app")
],
exclude:[
path.resolve(__dirname,"node_modules")
],
loader: "babel-loader",
options: {
presets: ["env","react"]
}
}
]
}
}