Files
wdp/task/webpack.react.js
T
2019-01-12 21:15:23 +08:00

118 lines
2.9 KiB
JavaScript

const path = require('path');
const chalk = require('chalk');
const webpack = require('webpack');
const webpackDevServer = require('webpack-dev-server');
const HtmlWebPackPlugin = require('html-webpack-plugin');
const util = require('./util');
let _webpackConfig = {
module:{
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
'@babel/preset-react',
'@babel/preset-env'
],
plugins: [
["@babel/plugin-proposal-function-bind"]
]
}
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.styl$/,
use: ['style-loader', 'css-loader', 'stylus-loader']
}
]
},
plugins:[]
};
exports.run = (paths, command) => {
console.log(paths);
//入口文件
_webpackConfig.entry = path.join(paths.targetPath, 'src', 'index.js');
//输出路径
_webpackConfig.output = {
path: path.join(paths.targetPath, 'dist'),
filename: 'index.js'
}
_webpackConfig.plugins.push(
new HtmlWebPackPlugin({
template: path.join(paths.targetPath, 'src', 'index.html'),
filename: path.join(paths.targetPath, 'dist', 'index.html'),
hash:true
})
);
//console.log(_webpackConfig,paths);
let _configJson = util.configJson(paths.targetPath);
let compiler = null;
if(command == 'init' || command == 'dev') {
_webpackConfig.mode = 'development';
let devServer = {
contentBase: path.join(paths.targetPath, "dist"),
compress: true,
host: 'localhost',
port: _configJson.port ? _configJson.port : 8088,
hot: true,
//open: true,
stats: {colors: true},
https: _configJson.https
}
if(_configJson.proxy) {
devServer.proxy = _configJson.proxy;
}
//node api 启动热更新
_webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
webpackDevServer.addDevServerEntrypoints(_webpackConfig, devServer);
compiler = webpack(_webpackConfig);
//node api 启动本地服务
let server = new webpackDevServer(compiler, devServer);
//console.log(devServer);
server.listen(devServer.port, 'localhost', (err) => {
if(err) {
console.log(err);
}else{
console.log(chalk.bold.green('服务启动: '+ devServer.contentBase +' : '+ devServer.https ? 'https' : 'http' + '://localhost:' + devServer.port));
}
});
}
if(command == 'pack') {
_webpackConfig.mode = 'production';
compiler = webpack(_webpackConfig, (err, stats) => {
if (err || stats.hasErrors()) {
//处理错误
console.error(err);
}
//处理完成
console.log(chalk.bold.green('打包编译完成!'));
console.log(chalk.bold.green('输出目录:' + path.join(paths.targetPath, "dist")));
});
}
}