webpack4+react项目搭建(一)
webpack配置
1.初始化项目
npm init
安装webpack
npm install webpack
2.创建配置目录结构
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.json
scripts: {
"start": "node ./scripts/start.js",
"build": "node ./scripts/build.js"
}
2)编写webpack配置
build/webpack.common.js
const 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.js
console.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.js
const 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.js
const webpackConfigCreator = require('./webpack.common');
const merge = require('webpack-merge');
const config = { };
const options = {
mode: 'production'
}
module.exports = merge(webpackConfigCreator(options), config)
build/webpack.dev.js
const webpackConfigCreator = require('./webpack.common');
const merge = require('webpack-merge');
const config = { };
const options = {
mode: 'development'
}
module.exports = merge(webpackConfigCreator(options), config)
scripts/build.js
const 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.js
const 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, 浏览器自动弹出窗口
共有 0 条评论