Skip to content

Instantly share code, notes, and snippets.

@mcattx
Created March 15, 2018 14:08
Show Gist options
  • Save mcattx/4ae55c1480ca9f4439dd2b7e35489252 to your computer and use it in GitHub Desktop.
Save mcattx/4ae55c1480ca9f4439dd2b7e35489252 to your computer and use it in GitHub Desktop.
[webpack4 配置] #JavaScript #JS
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const TARGET = process.env.npm_lifecycle_event;
const buildImagePath = TARGET === 'build' ? '../../images/sabi/[name].[ext]' : 'images/[name].[ext]'
const config = {
mode: 'development',
entry: {
index: './src/js/index.js',
game: './src/js/game.js'
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: "[name].min.js"
},
module: {
rules: [
{
// 为了处理 html 里的 img src 引用资源的问题引入
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: {
minimize: true
}
}
]
},
{
test: /.scss$/,
type: "javascript/auto",
include: [
path.resolve(__dirname, 'src/scss')
],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
// If you are having trouble with urls not resolving add this setting.
// See https://github.com/webpack-contrib/css-loader#url
minimize: true,
sourceMap: true
}
},
{
loader: 'postcss-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
})
},
{
test: /\.(png|jpg|gif)$/,
type: "javascript/auto",
use: [
{
loader: 'url-loader',
options: {
limit: 8192,
name: buildImagePath
// 开发环境这样配置,因为 webpack-dev-server 运行时文件都在内存
// name: 'images/[name].[ext]'
// 生产这样配置,这个路径相对于生产环境中 scss 和 images 目录路径
// name: '../../images/sabi/[name].[ext]'
}
}
]
}
]
},
devServer: {
port: 9000
},
resolve: {
alias: {
flexible$: path.resolve(__dirname, 'src/js/lib/flexible.min.js'),
zepto$: path.resolve(__dirname, 'src/js/lib/jquery-2.2.4.min.js')
},
},
plugins: [
// 使用 html-webpack-plugin 插件生成 2 个 HTML
new HtmlWebpackPlugin({
title: "撒币谁不会!汇桔社区撒币啦",
filename: 'index.html',
chunks: ['index'],
template: 'src/html/index.html'
}),
new HtmlWebpackPlugin({
title: '游戏页面',
filename: 'game.html',
chunks: ['game'],
template: 'src/html/game.html'
}),
// 把样式打包成独立的 css 文件
new ExtractTextPlugin({
filename: "[name].css"
}),
new webpack.ProvidePlugin({
$: 'zepto'
})
]
}
module.exports = config
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment