Webpack 搭建开发环境
//初始化一个项目
npm init
//安装webpack到开发环境中
npm install --save-dev webpack
//安装 webpack-dev-server
npm install --save-dev webpack-dev-server
//安装基础 loader
npm install --save-dev style-loader css-loader url-loader sass-loader node-sass babel-loader babel-core
//安装 html-webpack-plugin 插件 生成自动引用打包资源文件的静态页面
npm install --save-dev html-webpack-plugin
//安装 extract-text-webpack-plugin 插件 单独打包CSS
npm install --save-dev extract-text-webpack-plugin
创建配置文件 webpack.config.js
const path=require('path')
const HtmlWebpackPlugin=require('html-webpack-plugin')
const ExtractTextPlugin=require('extract-text-webpack-plugin')
module.exports={
entry:{
index:'./src/index.js'
},
output:{
path:path.resolve(__dirname,'dist'),//必须使用该方法生成绝对路径
filename:'[name].js' //[name]变量来源于entry中的键名
},
resolve:{
extensions:['.js','.css','.json','.scss'] //导入这些文件时可 省略后缀
},
devServer:{},
plugins:[
new HtmlWebpackPlugin({
title:'首页',
filename:'index.html',
template:'./index.html' //允许自定义一些模板
}),
new ExtractTextPlugin('[name].css')
],
module:{
rules:[
{
test:/\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
},
{
test:/\.scss$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: ['css-loader','sass-loader']
})
},
{
test:/\.(png|jpe?g|gif|svg)$/,
loader:'url-loader',
options:{
limit:10000
}
},
{
test:/\.js$/,
loader:'babel-loader',
exclude:path.resolve(__dirname,'node_modules') //不进行解析的目录
}
]
}
}
在package.json中的scripts增加启动脚本
"dev":"webpack-dev-server --open",
"build":"webpack",
运行、打包
//运行开发环境
npm run dev
//打包编译
npm run build
网友评论