webpack设置
1.初始化项目
npm init安装webpack
npm install webpack2.创建设置目次布局
build---webpack设置webpack.common.js webpack根本设置webpack.dev.js webpack开发设置webpack.prod.js webpack生产设置config---项目情况设置scripts---node脚本文件build.js 生产情况使用脚本start.js 开发情况使用脚本src---资源目次3.先实验一个简单设置
1)设置启动脚本下令
package.jsonscripts: { "start": "node ./scripts/start.js", "build": "node ./scripts/build.js"}2)编写webpack设置
build/webpack.common.jsconst path = require('path');module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "../dist"), filename: "bundle.js" }}3)编写开发模式运行脚本
scripts/build.js const webpack = require('webpack'); const webpackConfig = require('../build/webpack.common.js'); webpack(webpackConfig, (err, stats) => { if(err || stats.hasErrors()){ console.log("编译失败"); } });4)在入口编写一点内容
src/index.jsconsole.log('hello world');5)实行npm run build 下令,天生打包目次dist
4.设置开发服务器-webpack-dev-server
1)安装dev服务器和合并设置工具
npm install webpack-dev-server webpack-merge -D
- 改写webpack设置文件,common文件导出一个可传参数的根本设置天生器, prod和dev文件使用webpack-merge将通用设置和各自模式下的设置举行合并导出
build/webpack.common.jsconst path = require('path');function webpackCommonConfigCreator(options) { return { mode: options.mode, entry: "./src/index.js", output: { filename: "bundle.js", path: path.resolve(__dirname, "../dist") } }}module.exports = webpackCommonConfigCreator;build/webpack.prod.jsconst webpackConfigCreator = require('./webpack.common');const merge = require('webpack-merge');const config = { };const options = { mode: 'production'}module.exports = merge(webpackConfigCreator(options), config)build/webpack.dev.jsconst webpackConfigCreator = require('./webpack.common');const merge = require('webpack-merge');const config = { };const options = { mode: 'development'}module.exports = merge(webpackConfigCreator(options), config)scripts/build.jsconst webpack = require('webpack');const webpackConfig = require('../build/webpack.prod.js’);webpack(webpackConfig, (err, stats) => { if (err || stats.hasErrors()) { console.log("编译失败"); }})npm run build 输出正常
3)设置webpack-dev-server
build/webpack.dev.js
contentBase选项是server模式下的output, 开启server后,webpack会实时编译代码到内存
const path = require('path');const config = { devServer: { }}scripts/start.jsconst webpack = require('webpack'); const webpackDevServer = require('webpack-dev-server'); const webpackConfig = require('../build/webpack.dev.js'); const compiler = webpack(webpackConfig); const options = Object.assign({}, webpackConfig.devServer, { open: true }) const server = new webpackDevServer(compiler, options); server.listen(3000, '127.0.0.1', () => { console.log('Starting server on http://localhost:8080'); })运行下令npm run start, 欣赏器自动弹出窗口 |