温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解webpack 多入口配置

发布时间:2020-10-13 01:25:09 来源:脚本之家 阅读:129 作者:游云 栏目:web开发

同事套搭建vue项目,个人推荐了VUE官网的vue-cil的方式,http://cn.vuejs.org/guide/application.html

顺着官网的操作,我们可以本地测试起我们的项目 npm run dev,首先我们要理解webpack打包主要是针对js,查看下面生成的配置,首页是index.html,模版用的index.html,入口文件用的mian.js

详解webpack 多入口配置

//file build/webpack.base.conf.js
//entry 配置

module.exports = {
 entry: {
  app: './src/main.js'
 },
 //....

//file build/webpack.dev.conf.js
//html配置
  new HtmlWebpackPlugin({
   filename: 'index.html',
   template: 'index.html',
   inject: true
  })

1.上面的目录没办法满足我们多入口的要求,我们希望的是html放在一个views文件夹下面,相关业务应用的vue放在一起,对就是这个样子的

详解webpack 多入口配置

我们先简单的改动下我们的配置,来适应这个项目结构,再寻找其中的规律,来完成自动配置(index.html)

//file build/webpack.base.conf.js
//entry 配置

module.exports = {
 entry: {
  'index': './src/view/index/index.js',
  'login': './src/view/login/login.js',
 },
 //....

//file build/webpack.dev.conf.js
//html配置,index我们保留了根目录访问路径
  new HtmlWebpackPlugin({
   filename: 'index.html',
   template: './src/view/index/index.html',
   inject: true,
   chunks: ['index']
  }),
  new HtmlWebpackPlugin({
   filename: 'login/login.html', //http访问路径
   template: './src/view/login/login.html', //实际文件路径
   inject: true,
   chunks: ['login']
  })

2.规律出来了,我们只要按照这样的js和html的对应关系,就可以通过查找文件,来进行同一配置

var glob = require('glob')
function getEntry(globPath, pathDir) {
  var files = glob.sync(globPath);
  var entries = {},
    entry, dirname, basename, pathname, extname;

  for (var i = 0; i < files.length; i++) {
    entry = files[i];
    dirname = path.dirname(entry);
    extname = path.extname(entry);
    basename = path.basename(entry, extname);
    pathname = path.join(dirname, basename);
    pathname = pathDir ? pathname.replace(pathDir, '') : pathname;
    console.log(2, pathname, entry);
    entries[pathname] = './' + entry;
  }
  return entries;
}
//我们的key不是简单用的上一个代码的index,login而是用的index/index,login/login因为考虑在login目录下面还有register
//文件路径的\\和/跟操作系统也有关系,需要注意
var htmls = getEntry('./src/view/**/*.html', 'src\\view\\');
var entries = {};
var HtmlPlugin = [];
for (var key in htmls) {
  entries[key] = htmls[key].replace('.html', '.js')
  HtmlPlugin.push(new HtmlWebpackPlugin({
   filename: (key == 'index\\index' ? 'index.html' : key + '.html'), 
   template: htmls[key],
   inject: true,
    chunks: [key]
  }))
}

3.多入口配置就完成了,当然下面其实还有公共js提取的相关配置,如果项目里面用到了异步加载,即require.ensure,放在单独目录,进行匹配,按照上面的逻辑进行推理吧

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI