webpack基础配置
1、webpack.config.dev.js
// !开发环境 webpack 配置
// module.exports 是Common.js规范中模块的导出,类似: export/define
const path = require('path') // 引入磁盘处理模块 path
var HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextWebapckPlugin= require("extract-text-webpack-plugin")
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
mode: 'development',
entry: path.join(__dirname,'../src/index.js'),//entry表示入口文件
output: {
// output 表示出口目录
path: path.join(__dirname,'../dist'),
filename: `js/app[hash:6]-${ Date.now() }.js`
},
module: { // module这个属性是用于配置 loader 的
// rules 转换规则
rules: [
{
test: /\.css$/, // test 表示匹配规则
// use:[
// { loader: 'style-loader'},
// { loader: 'css-loader'},
// ]
use: ExtractTextWebapckPlugin.extract({
use: 'css-loader'
}) //不再需要style-loader
},
{
test: /\.scss$/,
use: [{
loader: "style-loader" // 将 JS 字符串生成为 style 节点
}, {
loader: "css-loader" // 将 CSS 转化成 CommonJS 模块
}, {
loader: "sass-loader" // 将 Sass 编译成 CSS
}]
},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
limit: 4000 // 图片大于5K,原样拷贝,小于5K,转成base64
}
}
]
}
]
},
devServer: {
proxy:{
// 标识符;目标源 https://m.douban.com/rexxar/api/v2/movie/modules
'/rexxar':{
target:'https://m.douban.com',
changeOrigin:true //使用http://loacalhost:9000 代替 http://m.douban.com 来发出请求
}
},
contentBase: path.join(__dirname,'../dist'),//当前服务器作用在dist文件下
open: true,//自动打开浏览器
hot: true,// 表示热更新【自动刷新】
port: 9000 // 指定服务器开启的端口
},
plugins: [
new HtmlWebpackPlugin({//这里控制将想要的html打包进去dist的,原本只是src中的东西打包进去的,现在想把public中的也打包进去
template:path.join(__dirname,'../public/index.html'), //模板是哪个文件
filename:path.join(__dirname,'../dist/index.html')//生成到这里
}),
new ExtractTextWebapckPlugin('css/[name][hash:6].css'),
new CopyWebpackPlugin([{
from: path.join(__dirname,'../public'),
to: path.join(__dirname,'../dist/static')
}])
],
devtool: 'source-map' //错误资源定制
}
2、package.json
"scripts": {
"start": "npm run dev && npm run server",
"server": "webpack-dev-server --config config/webpack.config.dev.js",
"dev": "webpack --config config/webpack.config.dev.js",
"build": "webpack --config config/webpack.config.prod.js"
},