快速配置webpack
程序员文章站
2022-10-17 11:22:35
区分开发模式和生产模式: npm run start——开发模式,启用devServer,文件的改动实时更新、刷新 npm run build——生产模式,打包文件到dist文件夹 ......
区分开发模式和生产模式:
npm run start——开发模式,启用devserver,文件的改动实时更新、刷新
npm run build——生产模式,打包文件到dist文件夹
// package.json
{
"name": "test",
"version": "1.0.0",
"description": "simple project",
"private": true,
"scripts": {
"build": "webpack --config webpack.config.js --color --progress --mode=production",
"start": "webpack-dev-server --open --mode=development"
},
"author": "yangxiang",
"license": "isc",
"devdependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"copy-webpack-plugin": "^4.5.2",
"css-loader": "^1.0.0",
"html-webpack-plugin": "^3.2.0",
"uglifyjs-webpack-plugin": "^1.3.0",
"webpack": "^4.17.2",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.7"
},
"dependencies": {
"mockjs": "^1.0.1-beta3"
}
}
// webpack.config.js
const path = require('path');
const webpack = require('webpack');
const htmlwebpackplugin = require('html-webpack-plugin');
const uglifyjsplugin = require('uglifyjs-webpack-plugin');
let webpackconfig = {
entry: './index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}, {
test: /\.(png|jpe?g|gif)(\?.*)?$/,
use: [{
loader: 'url-loader',
options: {
limit: 4096,
name: 'img/[name].[hash:8].[ext]'
}
}]
}, {
test: /\.css$/,
use: ['style-loader', 'css-loader']
}]
},
plugins: [
new htmlwebpackplugin({
template: './index.html'
})
]
};
if (process.env.node_env == "development") {
// 开发模式下的配置
webpackconfig.devserver = {
hot: true,
port: 8888
};
webpackconfig.plugins.concat(
new webpack.hotmodulereplacementplugin(),
new webpack.namedmodulesplugin(),
new webpack.noemitonerrorsplugin()
)
} else {
// 生产模式下的配置
webpackconfig.plugins.concat(
new uglifyjsplugin({
uglifyoptions: {
compress: {
warnings: false
}
},
sourcemap: true,
parallel: true
})
)
}
module.exports = webpackconfig;
上一篇: 女性长期月经不调易致哪些后果