使用webpack搭建react开发环境的方法(3)
之后打包便不会产生多余的文件.
编译es6和jsx
1.安装babel npm i babel-core babel-loader babel-preset-env babel-preset-react babel-preset-stage-0 -D babel-loader: babel加载器 babel-preset-env : 根据配置的 env 只编译那些还不支持的特性。 babel-preset-react: jsx 转换成js
2.添加.babelrc配置文件
{
"presets": ["env", "stage-0","react"] //从左向右解析
}
3.修改webpack.config.js
const path=require('path');
module.exports={
entry:'./src/index.js',
output:{
filename:'bundle.js',
path:path.resolve(__dirname,'dist')
},
//以下是新增的配置
devServer:{
contentBase: "./dist",//本地服务器所加载的页面所在的目录
historyApiFallback: true,//不跳转
inline: true//实时刷新
},
module:{
rules:[
{
test:/\.js$/,
exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度
use:{
loader:'babel-loader'
}
}
]
}
};
开发环境与生产环境分离
1.安装 webpack-merge
npm install --save-dev webpack-merge
2.新建一个名为webpack.common.js文件作为公共配置,写入以下内容:
const path=require('path');
let webpack=require('webpack');
let HtmlWebpackPlugin=require('html-webpack-plugin');
let CleanWebpackPlugin=require('clean-webpack-plugin');
module.exports={
entry:['babel-polyfill','./src/index.js'],
output:{
//添加hash可以防止文件缓存,每次都会生成4位hash串
filename:'bundle.[hash:4].js',
path:path.resolve(__dirname,'dist')
},
plugins:[
new HtmlWebpackPlugin({
template:'./src/index.html',
hash:true, //会在打包好的bundle.js后面加上hash串
}),
//打包前先清空
new CleanWebpackPlugin('dist'),
new webpack.HotModuleReplacementPlugin() //查看要修补(patch)的依赖
],
module:{
rules:[
{
test:/\.js$/,
exclude:/(node_modules)/, //排除掉nod_modules,优化打包速度
use:{
loader:'babel-loader'
}
}
]
}
};
3.新建一个名为webpack.dev.js文件作为开发环境配置
const merge=require('webpack-merge');
const path=require('path');
let webpack=require('webpack');
const common=require('./webpack.common.js');
module.exports=merge(common,{
devtool:'inline-soure-map',
mode:'development',
devServer:{
historyApiFallback: true, //在开发单页应用时非常有用,它依赖于HTML5 history API,如果设置为true,所有的跳转将指向index.html
contentBase:path.resolve(__dirname, '../dist'),//本地服务器所加载的页面所在的目录
inline: true,//实时刷新
open:true,
compress: true,
port:3000,
hot:true //开启热更新
},
plugins:[
//热更新,不是刷新
new webpack.HotModuleReplacementPlugin(),
],
});
内容版权声明:除非注明,否则皆为本站原创文章。
