webpack4.0+vue2.0利用批处理生成前端单页或多页应用(4)

<body> <!--开发环境--> <div></div> <script type="text/javascript" src="https://www.jb51.net/lib/jquery/jquery.min.js"></script> <script type="text/javascript" src="https://www.jb51.net/lib/bootstrap/js/bootstrap.min.js"></script> <script type="text/javascript" src="https://www.jb51.net/index.js"></script> </body>

index.js 就是之前的入口文件,必须要写进html文件里的,因为没有用 HtmlWebpackPlugin 做模板的映射,当真正在开发环境下使用 (template.html) 模板是这样子的

<body> <!--生产环境--> <div></div> <script type="text/javascript" src="https://www.jb51.net/resources/lib/jquery/jquery.min.js"></script> <script type="text/javascript" src="https://www.jb51.net/resources/lib/bootstrap/js/bootstrap.min.js"></script> </body>

所以分了两个模板去渲染页面

webpack4 多页配置(single)

多页应用的目录结构

build --views --index.html --404.html --build.js --config.js --dev-server.js --utils.js --webpack.base.conf.js --webpack.dev.conf.js --webpack.prod.conf.js src --conponents --css --font --images --mixins --pages //页面目录 --new --index.js //入口 --new.vue static --jquery mode_modules

build目录下有三个文件有些改动

dev-server.js 去掉了视图目录指向

因为是多页的,这里是获取src目录下的一级目录做为路由

//这个获取的是内存路径 app.get('/:viewname?', function(req, res, next) { var viewname = req.params.viewname ? req.params.viewname + '.html' : 'main.html'; var filepath = path.join(compiler.outputPath, viewname); compiler.outputFileSystem.readFile(filepath, function(err, result) { if (err) { res.send('can\'t not find the file: ' + filepath).end; return; } res.set('content-type', 'text/html'); res.send(result); res.end(); }); });

然后是 webpack.dev.conf.js 里加了这一段

let entryObj = utils.getFileName(); Object.keys(entryObj).forEach((name) => { webpackConfig.entry[name] = ['webpack-hot-middleware/client?noInfo=true&reload=true'].concat(entryObj[name]); let plugin = new htmlWebpackPlugin({ filename: name + '.html', template: config.build.templatePath, inject: true, chunks: [name] }); webpackConfig.plugins.push(plugin); })

获取src目录下的每个文件做为入口进行模板渲染

同样在 webpackprod.conf.js 也需要加上

let entryObj = utils.getFileName(); Object.keys(entryObj).forEach((name) => { webpackConfig.entry[name] = entryObj[name]; let plugin = new HtmlWebpackPlugin({ chunks: ['manifest', name], filename: name + '.html', template: config.build.templatePath, inject: true, environment: 'resources', minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: false } }); webpackConfig.plugins.push(plugin); })

这里多了一个 environment 他是插入模板的一个变量,为区分开发和生产环境路径

<body> <!--生产环境--> <div></div> <script type="text/javascript" src="<%= htmlWebpackPlugin.options.environment %>/lib/jquery/jquery.min.js"></script> <script type="text/javascript" src="<%= htmlWebpackPlugin.options.environment %>/lib/bootstrap/js/bootstrap.min.js"></script> </body>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/9cd0a69d50b827cb849661203d1315b7.html