Skip to content

Commit

Permalink
update to webpack4 (#889)
Browse files Browse the repository at this point in the history
  • Loading branch information
PanJiaChen authored Aug 15, 2018
1 parent 1df59cc commit 378ca2c
Show file tree
Hide file tree
Showing 12 changed files with 284 additions and 248 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ npm run build:prod
# --report to build with bundle size analytics
npm run build:prod --report

# --generate a bundle size analytics. default: bundle-report.html
npm run build:prod --generate_report

# --preview to start a server in local to preview
npm run build:prod --preview

Expand Down
5 changes: 4 additions & 1 deletion README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,10 @@ npm run build:prod
## 其它
```bash
# --report to build with bundle size analytics
npm run build:prod --report
npm run build:prod

# --generate a bundle size analytics. default: bundle-report.html
npm run build:prod --generate_report

# --preview to start a server in local to preview
npm run build:prod --preview
Expand Down
51 changes: 31 additions & 20 deletions build/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,49 +8,60 @@ const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
var connect = require('connect');
var connect = require('connect')
var serveStatic = require('serve-static')

const spinner = ora('building for ' + process.env.env_config + ' environment...')
const spinner = ora(
'building for ' + process.env.env_config + ' environment...'
)
spinner.start()

rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
process.stdout.write(
stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n'
)

if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}

console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
console.log(
chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
" Opening index.html over file:// won't work.\n"
)
)

if (process.env.npm_config_preview) {
const port = 9526
const host = "http://localhost:" + port
const host = 'http://localhost:' + port
const basePath = config.build.assetsPublicPath
const app = connect()

app.use(basePath, serveStatic('./dist', {
'index': ['index.html', '/']
}))
app.use(
basePath,
serveStatic('./dist', {
index: ['index.html', '/']
})
)

app.listen(port, function () {
console.log(chalk.green(`> Listening at http://localhost:${port}${basePath}`))
});
app.listen(port, function() {
console.log(
chalk.green(`> Listening at http://localhost:${port}${basePath}`)
)
})
}
})
})
24 changes: 17 additions & 7 deletions build/check-versions.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@ const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')

function exec (cmd) {
return require('child_process').execSync(cmd).toString().trim()
function exec(cmd) {
return require('child_process')
.execSync(cmd)
.toString()
.trim()
}

const versionRequirements = [
Expand All @@ -24,23 +27,30 @@ if (shell.which('npm')) {
})
}

module.exports = function () {
module.exports = function() {
const warnings = []

for (let i = 0; i < versionRequirements.length; i++) {
const mod = versionRequirements[i]

if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
warnings.push(mod.name + ': ' +
chalk.red(mod.currentVersion) + ' should be ' +
chalk.green(mod.versionRequirement)
warnings.push(
mod.name +
': ' +
chalk.red(mod.currentVersion) +
' should be ' +
chalk.green(mod.versionRequirement)
)
}
}

if (warnings.length) {
console.log('')
console.log(chalk.yellow('To use this template, you must update following to modules:'))
console.log(
chalk.yellow(
'To use this template, you must update following to modules:'
)
)
console.log()

for (let i = 0; i < warnings.length; i++) {
Expand Down
49 changes: 28 additions & 21 deletions build/utils.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
'use strict'
const path = require('path')
const config = require('../config')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const packageConfig = require('../package.json')

exports.assetsPath = function (_path) {
const assetsSubDirectory = process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory
exports.assetsPath = function(_path) {
const assetsSubDirectory =
process.env.NODE_ENV === 'production'
? config.build.assetsSubDirectory
: config.dev.assetsSubDirectory

return path.posix.join(assetsSubDirectory, _path)
}

exports.cssLoaders = function (options) {
exports.cssLoaders = function(options) {
options = options || {}

const cssLoader = {
Expand All @@ -30,8 +31,22 @@ exports.cssLoaders = function (options) {
}

// generate loader string to be used with extract text plugin
function generateLoaders (loader, loaderOptions) {
const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader]
function generateLoaders(loader, loaderOptions) {
const loaders = []

// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
loaders.push(MiniCssExtractPlugin.loader)
} else {
loaders.push('vue-style-loader')
}

loaders.push(cssLoader)

if (options.usePostCSS) {
loaders.push(postcssLoader)
}

if (loader) {
loaders.push({
Expand All @@ -42,32 +57,24 @@ exports.cssLoaders = function (options) {
})
}

// Extract CSS when that option is specified
// (which is the case during production build)
if (options.extract) {
return ExtractTextPlugin.extract({
use: loaders,
fallback: 'vue-style-loader'
})
} else {
return ['vue-style-loader'].concat(loaders)
}
return loaders
}

// https://vue-loader.vuejs.org/en/configurations/extract-css.html
return {
css: generateLoaders(),
postcss: generateLoaders(),
less: generateLoaders('less'),
sass: generateLoaders('sass', { indentedSyntax: true }),
sass: generateLoaders('sass', {
indentedSyntax: true
}),
scss: generateLoaders('sass'),
stylus: generateLoaders('stylus'),
styl: generateLoaders('stylus')
}
}

// Generate loaders for standalone style files (outside of .vue)
exports.styleLoaders = function (options) {
exports.styleLoaders = function(options) {
const output = []
const loaders = exports.cssLoaders(options)

Expand Down
19 changes: 1 addition & 18 deletions build/vue-loader.conf.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,5 @@
'use strict'
const utils = require('./utils')
const config = require('../config')
const isProduction = process.env.NODE_ENV === 'production'
const sourceMapEnabled = isProduction
? config.build.productionSourceMap
: config.dev.cssSourceMap

module.exports = {
loaders: utils.cssLoaders({
sourceMap: sourceMapEnabled,
extract: isProduction
}),
cssSourceMap: sourceMapEnabled,
cacheBusting: config.dev.cacheBusting,
transformToRequire: {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
//You can set the vue-loader configuration by yourself.
}
19 changes: 13 additions & 6 deletions build/webpack.base.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const { VueLoaderPlugin } = require('vue-loader')
const vueLoaderConfig = require('./vue-loader.conf')

function resolve (dir) {
function resolve(dir) {
return path.join(__dirname, '..', dir)
}

Expand All @@ -27,14 +28,15 @@ module.exports = {
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
publicPath:
process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'@': resolve('src'),
'@': resolve('src')
}
},
module: {
Expand All @@ -48,7 +50,11 @@ module.exports = {
{
test: /\.js$/,
loader: 'babel-loader?cacheDirectory',
include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
include: [
resolve('src'),
resolve('test'),
resolve('node_modules/webpack-dev-server/client')
]
},
{
test: /\.svg$/,
Expand Down Expand Up @@ -85,6 +91,7 @@ module.exports = {
}
]
},
plugins: [new VueLoaderPlugin()],
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
Expand Down
36 changes: 22 additions & 14 deletions build/webpack.dev.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,20 @@ const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

function resolve (dir) {
function resolve(dir) {
return path.join(__dirname, '..', dir)
}

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
mode: 'development',
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
rules: utils.styleLoaders({
sourceMap: config.dev.cssSourceMap,
usePostCSS: true
})
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
Expand All @@ -39,16 +43,14 @@ const devWebpackConfig = merge(baseWebpackConfig, {
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
poll: config.dev.poll
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
Expand All @@ -57,7 +59,7 @@ const devWebpackConfig = merge(baseWebpackConfig, {
favicon: resolve('favicon.ico'),
title: 'vue-element-admin',
path: config.dev.assetsPublicPath + config.dev.assetsSubDirectory
}),
})
]
})

Expand All @@ -73,14 +75,20 @@ module.exports = new Promise((resolve, reject) => {
devWebpackConfig.devServer.port = port

// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
devWebpackConfig.plugins.push(
new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [
`Your application is running here: http://${
devWebpackConfig.devServer.host
}:${port}`
]
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
})
)

resolve(devWebpackConfig)
}
Expand Down
Loading

0 comments on commit 378ca2c

Please sign in to comment.