The introduction
Following webpack-Vue scaffolding Build, it’s not possible to write and pack and see what happens during development. Or some environmental factors (such as interface is not developed, cross domain, etc.) we may not be able to do debugging. So we this article to discuss with you, how to add local debugging in their scaffolding required elements, if in the article, or which aspects of the error or want to discuss, welcome to the end of the article message I will reply to you as soon as possible (overtime dog is not easy !!!!)
start
The entire file structure has been changed to the following after the previous iterations
. ├ ─ ─ node_modules ├ ─ ─ dist / / documents after packaging │ ├ ─ ─ images │ │ └ ─ ─ timg. Cff62bc. Jpeg │ ├ ─ ─ index. The HTML │ ├ ─ ─ the main, js │ └ ─ ─ Styles.css ├── Package-Lock. json ├─ SRC │ ├─ app.vue │ ├─ assets │ ├─ timg.jpeg │ ├.css ├─ Package-Lock. json ├─ SRC │ ├─ app.vue │ ├─ assets │ ├─ timg.jpeg │ ├── ├─ ├─ ├─ ├─ ├.config.js //Copy the code
So if you want to know what your style is, what your code is doing. First, we need to run NPM run build to package, and then open the package file in index.html to browse the corresponding changes. It’s a bit of a problem. So is there any way we can make code changes and see them in real time? The answer is there, but first we may need to make a simple change to our file itself
webpack-merge
Merge WebPack-merge is a simple tool that allows you to quickly merge two webpack configuration items. However, I understand that this tool is similar to the recursive version of Object.assign, although some special key handling may be different. For example, plugins are more like plugins, so why do we use them?
I think it’s easy to understand that the webPack configuration that we might need for different environments may not be consistent. Not every environment needs to do things like compile Babel, package report output, etc., so we might have different configurations for different environments. However, it is not completely different. There may be some configurations that make sense, so we need webpack-Merge to help us integrate the configurations. NPM install webpack-merge –save and separate the following file directories. (I have added the entire code of this article below, and the differences will be introduced in the following pages. Please don’t worry if you don’t understand.)
- webpack.base.js
// webpack.base.js
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const kb = 1024
const mb = 1000 * kb
module.exports = {
entry: path.resolve(__dirname, './src/main.js'),
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'}},module: {
rules: [{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'.options: {
presets: [['@babel/preset-env',
{
useBuiltIns: "usage".// Use it before importing it
corejs: 3 // Specify the version number}]],plugins: [["@babel/plugin-transform-runtime",
{
corejs: 3 // Specify the version number}]}}}, {test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'vue-style-loader'.use: [{
loader: 'css-loader'.options: {
esModule: false}},'sass-loader']})}, {test: /\.(png|jpg|jpeg|gif)$/i,
use: [{
loader: 'url-loader'.options: {
limit: 10 * kb,
name: 'images/[name].[hash:7].[ext]'.publicPath: '/'.esModule: false},},],},plugins: [
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html'.template: path.resolve(__dirname, './index.html')}),new ExtractTextPlugin('styles.css')]}Copy the code
- webpack.dev.js
// webpack.dev.js
const path = require('path');
const baseConfig = require('./webpack.base.js')
const { merge } = require('webpack-merge');
const webpack = require('webpack')
const devObj = {
mode: 'development'.output: {
filename: '[name].js'.path: path.resolve(__dirname, './dist'),
publicPath: '/'
},
devtool: 'cheap-module-eval-source-map'.devServer: {
clientLogLevel: 'info'.host: "0.0.0.0".port: 8080.hot: true.open: true.compress: true.contentBase: false.publicPath: '/'
},
plugins: [
// Ensure that the generated resource data is correct
new webpack.NoEmitOnErrorsPlugin(),
// Generate source map instead of devTools
new webpack.SourceMapDevToolPlugin()
]
}
module.exports = merge([baseConfig, devObj])
Copy the code
- webpack.prod.js
// webpack.prod.js
const path = require('path');
const {
CleanWebpackPlugin
} = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const baseConfig = require('./webpack.base.js')
const { merge } = require('webpack-merge')
const prodObj = {
mode: 'production'.// The exit of the file is the file we want to generate
output: {
// Where [name] is an entry name
filename: '[name].js'.path: path.resolve(__dirname, './dist'),
publicPath: '/'
},
plugins: [
new CleanWebpackPlugin(),
new BundleAnalyzerPlugin()
]
}
module.exports = merge([baseConfig, prodObj])
Copy the code
- webpack.serve.js
const path = require('path');
const devObj = require('./webpack.dev.js')
const { merge } = require('webpack-merge');
const webpack = require('webpack')
const serveObj = {
entry: ['webpack-hot-middleware/client.js', path.resolve(__dirname, './src/main.js')].plugins: [
/ / hot replacement
new webpack.HotModuleReplacementPlugin()
]
}
module.exports = merge([devObj, serveObj])
Copy the code
The above is the complete code of this article, not to say that it is perfect, but it can meet a relatively basic configuration items, and is conducive to learning, and I will follow you to optimize according to some of my ideas. First of all, let’s make a general summary of the above documents. Webpack.dev. js and webpack.serve.js are the two files that have changed the content of these files, so we will focus on these two files in the next article.
webpack.dev.js
devtool
The official Chinese document actually explains what this field is for, but I’m going to talk about it here. This field is used to configure the source Map type needed during debugging. Some of you may not know what source map is. The simple answer is that our packaged code is one-line and confusing. It will certainly be inconvenient if we debug in this way, so we need the source map file to help us record the location of some original corresponding lines of code, and facilitate our debug operations in the browser side. When more detailed content can be learned through teacher Ruan Yifeng JavaScript Source Map.
As for the Webpack official, there are actually a number of different configuration options available to us, as shown below
I don’t know if I’m looking at this. Ha ha ha ha ha ha but actually, he is there are some rules to follow ~ I also see on the nuggets have a big article was written by clearer here also share with you * * * * to watch, click here I choose cheap-module-eval-source-map as the parameter configuration of devTool. Specifically, we can locate errors more accurately in the development process and use ~ more conveniently
devServer
DevServer is actually short for Webpack-dev-server. The main purpose is to facilitate the development environment, for developers to provide a test server, so this configuration item actually has a lot of content, here I select some more basic fields to introduce ~
host
The IP address to start the local service is 0.0.0.0 in most cases. Because when we fill in 0.0.0.0, we can access either 127.0.0.1 or 192.168.1.xxx. Writing one or the other doesn’t do the trick.
port
Local service port, generally choose the common 8080 can, of course, can also be modified according to your needs
hot
Enable webpack module hot replacement feature, this property is mainly convenient in the case of local development, development can not refresh the page, to see the latest code situation, generally we in the development environment set to true
open
Whether to open the corresponding service address host:port in the browser and set the development environment to true when starting the service
compress
Whether to start the gzip, whether it is primarily a local service for resources for gzip compression, speed up the request of local resources, local development is set to true, about gzip itself may also be some friends don’t understand is what, simply speaking, is a kind of server and browser side support coding format, In many production environments, we also use gzip to reduce the size of static files by one, reducing the transfer time
clientLogLevel
Webpack is mainly for some of the log print type Settings, can be set to different types to facilitate their own differentiation, the code is simple as follows:
var INFO = 'info';
var WARN = 'warn';
var ERROR = 'error';
var DEBUG = 'debug';
var TRACE = 'trace';
var SILENT = 'silent'; // deprecated
// TODO: remove these at major released
// https://github.com/webpack/webpack-dev-server/pull/1825
var WARNING = 'warning';
var NONE = 'none'; // Set the default log level
log.setDefaultLevel(INFO);
function setLogLevel(level) {
switch (level) {
case INFO:
case WARN:
case ERROR:
case DEBUG:
case TRACE:
log.setLevel(level);
break;
// deprecated
case WARNING:
// loglevel's warning name is different from webpack's
log.setLevel('warn');
break;
// deprecated
case NONE:
case SILENT:
log.disableAll();
break;
default:
log.error("[WDS] Unknown clientLogLevel '".concat(level, "'")); }}Copy the code
proxy
Configure a reverse proxy to solve cross-domain problems (this feature is often used!) Click to view the specific configuration
In fact, devServer provides very powerful capabilities. We have only made some basic introductions. If you are interested, you can go into them by yourself
webpack.NoEmitOnErrorsPlugin
Emit is actually exposed as a hook in the WebPack Compiler
The name of the plugin is very clear. When errors occur during compilation, or at other stages of the WebPack run, the corresponding resources are not generated to the directory.
So the main use of this plug-in is to avoid generating some error resources ~ is also a relatively practical small plug-in
run
After configuring these options, we can open our package.json file and add the following command
"scripts": {...// Add the following line
"dev": "webpack-dev-server --inline --progress --config webpack.dev.js". },Copy the code
Then run NPM run dev from the command line to open our local static resources at http://0.0.0.0:8080
webpack.serve.js
So what is webpack.serve.js for when we have all the local service stuff in Dev? Look at webpack-dev-middleware and Webpack-hot-middleware
webpack-dev-middleware
Webpack-dev-middleware is an express middleware that actually supports webpack’s native debug service. We used webpack-dev-server to start a local service, but since it is built in, there are limitations to how many configurable items you want to start multiple services at the same time, or how many things you want to do in node code. That’s a lot of work, but starting local services with Webpack-dev-middleware gives you more flexibility. In addition to webpack itself, you may want to add some native mock servers, or some more flexible rules are possible, so how do we use this
According to github, we can use Node xxx.js by simply creating xxx.js in the directory and adding the following code
const webpack = require('webpack');
const middleware = require('webpack-dev-middleware');
const compiler = webpack({
// webpack options
});
const express = require('express');
const app = express();
app.use(
middleware(compiler, {
// webpack-dev-middleware options})); app.listen(3000.() = > console.log('Example app listening on port 3000! '));
Copy the code
Webpack-dev-middleware can be used for middleware
webpack-hot-middleware
Webpack-hot-middleware Github is hot in devServer. But the configuration items here may be a little more ~
server.js
So now that we know what these two middleware do, NPM install Express Webpack-dev -middleware webpack-hot-middleware –save-dev
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const app = express();
const config = require('./webpack.serve.js');
const compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
publicPath: '/'
}));
app.use(require("webpack-hot-middleware")(compiler));
app.listen(3000.function () {
console.log('Example app listening on port 3000! \n');
});
Copy the code
Next, add the following instructions to package.json
"scripts": {...// Add the following line
"start": "node server.js". },Copy the code
Run NPM run start to open it at localhost:3000
Existing problems
So at this point, we can basically meet most of the needs of local development, but if there are some more development requirements or optimizations, why don’t we continue to see ~
General configuration
In fact, many common configuration items of Webpack are scattered in several configuration files. If all of them become one Obj, it will be very redundant. Therefore, we may try to extract a common common configuration item to facilitate our normal configuration requirements
performance
In most cases in our build, only some basic implementations are considered, but for packaged file subcontracting, packaging is often almost never considered
Development experience
At present, the introduction of modules between modules, or import and require for import, so we have no way according to the file directory or distinguish some common modules for automatic import, including some global parameters, methods and so on
So the above mentioned are some points THAT I can temporarily think of that need to be optimized together, and I will put them in the optimization of Webpack-Vue scaffolding to solve with you
At the end
This article bring so a dev is one of the most basic configuration, may be is just not enough for most of the students, so I’ll keep my side know some of the more useful tips, configuration, plug-in, loader in the next issue of optimizing the article introduces a unified explanation (long), interested friends remember the thumb up, Leave a message and follow me