Home  >  Article  >  Web Front-end  >  About webpack project configuration

About webpack project configuration

亚连
亚连Original
2018-06-21 16:27:491214browse

This article mainly introduces the detailed configuration issues of webpack compilation of multi-page vue projects. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

This article mainly introduces the configuration issues of webpack compiling multi-page vue projects and shares them with everyone. The details are as follows:

Under normal circumstances, how to build a vue project The steps are:

1, install nodejs environment

2, install vue-cli

cnpm install vue-cli -g

3, build vue project

vue init webpack-simple vue-cli-multipage-demo

4, install project dependencies Package

cnpm install

5, run the project in the development environment:

npm run dev

Through the above steps, a simple vue project development environment is basically set up, and the next work is to fill in the code .

I recently discovered a problem when I was refactoring a front-end code. The project built using this scaffolding could not meet my needs. In fact, this requirement is a bit contrary to the original intention of our Vue. What Vue develops is a single page. Application (SPA), here I need it to achieve multi-page effects. What does that mean? For example: when we are developing web pages, sometimes when we click a link, the browser will open a new tab page to display our content. At this time, there are actually multiple pages. The newly opened page is actually already The page that does not belong to us before (SPA) actually uses routing to display multiple pages on the main page. But at this time, the newly opened page has been separated from the main page.

The webpack configuration file of the project built through the vue-cli scaffolding supports single-page application development. It has only one entry file. And only one page will be produced in the end. How can I meet my needs and make webpack convenient for multiple pages at the same time? In fact, it is relatively simple. I only need to slightly modify webpack and it will be fine.

First we need to add a method to obtain the file path in the folder in the utils.js file under the build file. This method parses the target file into the form of an object.
utils.js

var glob = require("glob");//分析文件夹中文件路径的第三方模块
exports.getEntry = function(globPath) {
 var entries = {},
 basename, tmp, pathname;
 if (typeof (globPath) != "object") {
 globPath = [globPath]
 }
 globPath.forEach((itemPath) => {
 glob.sync(itemPath).forEach(function (entry) {
  basename = path.basename(entry, path.extname(entry));
  if (entry.split('/').length > 4) {
  tmp = entry.split('/').splice(-3);
  pathname = tmp.splice(0, 1) + '/' + basename; // 正确输出js和html的路径
  entries[pathname] = entry;
  } else {
  entries[basename] = entry;
  }
 });
 });
 return entries;
}

Then modify the wenpack.base.conf.js file and modify the entry file. The original file is a single file. Now you need to change the single file entry to a multi-file entry.

webpack.dev.conf.js

var path = require('path')
var config = require('../config')
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')
var glob = require('glob');
var entries = utils.getEntry(['./src/module/**/*.js']); // 获得多页面的入口js文件
var env = process.env.NODE_ENV
// various preprocessor loaders added to vue-loader at the end of this file
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd
module.exports = {
 entry: entries,//这是通过前面新增的方法获取的文件路径对象
 output: {
 path: config.build.assetsRoot,
 publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
 filename: '[name].js'
 }
 ...
}

The webpack.dev and conf.js files need to be modified below. The main purpose here is to modify the original configured homepage. Multiple pages need to be configured here

webpack.dev.conf.js

var path = require('path');
var config = require('../config')
var webpack = require('webpack')
var merge = require('webpack-merge')
var utils = require('./utils')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
 baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
 ...
});
//新增
var pages =utils.getEntry(['./src/module/*.html','./src/module/**/*.html']);
for (var pathname in pages) {
 // 配置生成的html文件,定义路径等
 var conf = {
 filename: pathname + '.html',
 template: pages[pathname], // 模板路径
 inject: true,    // js插入位置
 chunksSortMode: 'dependency'
 };
 if (pathname in module.exports.entry) {
 conf.chunks = ['manifest', 'vendor', pathname];
 conf.hash = true;
 }
 module.exports.plugins.push(new HtmlWebpackPlugin(conf));
}

If the conf object of new HtmlWebpackPlugin is changed here, the original configuration is a single html, and now multiple html configuration objects are generated by looping the pages object.

Through the above configuration, when we execute npm run dev, webpack can facilitate multiple pages at the same time, and then insert the js file configured in wenpack.base.conf.js into the corresponding html page.

At this time we run the project npm run dev and then we can access different pages. We need to pay attention here. Since we need to manage multiple pages, we should create a directory under src specifically to access different pages. page. This way the project structure looks clearer and is easier to maintain.

This is a demo address I wrote. If you are interested, you can pull it down and take a look at vue-cli-multi-page

After running it, visit http://localhost:8080/module/ index.html, and then click the button to open a new page.

The above configuration is only for the development environment. Finally, the configuration file webpack.prod.conf.js of the production environment also needs to be modified, so that multiple html files can be generated in dist at the same time during production packaging.

webpack.prod.conf:

var path = require('path')
var config = require('../config')
var utils = require('./utils')
var webpack = require('webpack')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var CleanPlugin = require('clean-webpack-plugin')//webpack插件,用于清除目录文件
var env = config.build.env
var webpackConfig = merge(baseWebpackConfig, {
...
}
//这里是修改的部分,和webpack.dev.conf.js的修改是一样的
module.exports = webpackConfig
var pages =utils.getEntry(['./src/module/**/*.html']);
for (var pathname in pages) {
 // 配置生成的html文件,定义路径等
 var conf = {
 filename: pathname + '.html',//生成 html 文件的文件名
 template: pages[pathname], // 根据自己的指定的模板文件来生成特定的 html 文件。这里的模板类型可以是任意你喜欢的模板,可以是 html, jade, ejs, hbs, 等等,但是要注意的是,使用自定义的模板文件时,需要提前安装对应的 loader,
 inject: true,    // 注入选项。有四个选项值 true, body, head, false.true:默认值,script标签位于html文件的 body 底部,body:同 true,head:script 标签位于 head 标签内,false:不插入生成的 js 文件,只是单纯的生成一个 html 文件
 // necessary to consistently work with multiple chunks via CommonsChunkPlugin
 chunksSortMode: 'dependency'
 };
 if (pathname in module.exports.entry) {
 conf.chunks = ['manifest', 'vendor', pathname];
 conf.hash = true;
 }
 module.exports.plugins.push(new HtmlWebpackPlugin(conf));
}

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Using modular development in vuejs

How to implement the array update function in VUE

What should you pay attention to when optimizing Vue projects?

The above is the detailed content of About webpack project configuration. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn