https://webpack.docschina.org/api/node/
webpack-demo
├── src
│ └── App.vue
├── webpack-node.js
├── webpack.config.js
└── package.json
package.json
{
"name": "vue-server-renderer-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build:server": "cross-env BASE_BUILD=server npx webpack",
"build:client": "cross-env BASE_BUILD=client npx webpack",
"dev": "node ./server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"vue": "^2.6.14",
"vue-router": "^3.5.2",
"vue-server-renderer": "^2.6.14"
},
"devDependencies": {
"vue-loader": "^15.9.8",
"vue-loader-plugin": "^1.3.0",
"vue-template-compiler": "^2.6.14",
"webpack": "^5.52.1",
"webpack-cli": "^4.8.0"
}
}
webpack.config.js
const path = require('path')
const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
module.exports = {
mode: 'development',
devtool: 'source-map',
entry: {
app: './src/App.vue'
},
output: {
path: path.join(__dirname, "./dist/"), //文件输出目录
filename: '[name].js',
chunkFilename: '[name].common.js',
},
module: {
rules: [
{
test: /\.vue$/,
use: [
'vue-loader',
]
}
]
},
externals: {
vue: 'Vue',
},
plugins: [
new webpack.DefinePlugin({
'process.env.BASE_BUILD': `'${process.env.BASE_BUILD}'`
}),
new VueLoaderPlugin()
]
}
App.vue
<script>
export default {
template: `<div id="root"><router-view></router-view></div>`,
}
</script>
webpack-node.js
webpack 1
const webpack = require('webpack');
const config = require('./webpack.config.js')
webpack(config, (err, stats) => { // [Stats Object](#stats-object)
if (err || stats.hasErrors()) {
// [在这里处理错误](#error-handling)
console.log(err)
return
}
// 处理完成
console.log('webpack build 成功')
});
webpack 2
// Compiler 实例
// 如果你掉用 webpack(config),不传入回调函数,会返回一个Compiler实例
const webpack = require('webpack');
const config = require('./webpack.config.js')
const compiler = webpack(config)
compiler.run((err, stats) => { // [Stats Object](#stats-object)
if (err || stats.hasErrors()) {
// [在这里处理错误](#error-handling)
console.log(err)
return
}
// 处理完成
console.log('webpack build 成功')
compiler.close((closeErr) => {
// 不要忘记关闭编译器,这样低优先级的工作(比如持久缓存)就有机会完成。
});
})
webpack 3
/**
* 调用 watch 方法会触发 webpack 执行,但之后会监听变更(很像 CLI 命令: webpack --watch),
* 一旦 webpack 检测到文件变更,就会重新执行编译。 该方法返回一个 Watching 实例。
*/
const compiler = webpack(config);
const watching = compiler.watch({
// [watchOptions](/configuration/watch/#watchoptions) 示例
aggregateTimeout: 300,
poll: undefined
}, (err, stats) => { // [Stats Object](#stats-object)
// 这里打印 watch/build 结果...
console.log(stats);
});
// 关闭 Watching
watching.close((closeErr) => {
console.log('Watching Ended.');
});
// 使用 watching.invalidate,
// 你可以手动使当前编译循环(compiling round)无效, 而不会停止监听进程(process):
watching.invalidate();