• vue2 p10 webpack服务器插件webpackdevserver自动打包更新显示内容、htmlwebpackplugin自动访问src下html文件


    一、webpack-dev-server

    js脚本修改后每次要重新运行npm run dev重新打包,非常麻烦,
    因此需要一个自动检测代码有无修改,自动打包功能
    npm i -D webpack webpack-cli webpack-dev-server html-webpack-plugin

    webpack.config.js配置

    const path=require('path')
    
    module.exports={
        mode:'development',
        entry:path.join(__dirname,'./src/index.js'),
        output:{
            path:path.join(__dirname,'./dist'),
            filename:'ok.js'
        }
    }
    

    1 安装 webpack-dev-server

    运行如下的命令,即可在项目中安装此插件:

    npm install webpack-dev-server@3.11.2 -D
    

    2 配置 webpack-dev-server

    ① 修改 package.json -> scripts 中的 dev 命令如下:

    "scripts": {
        "dev": "webpack serve"
      }
    

    1.2 index.html中引用打包后文件改成:

    <script src='/ok.js'></script>
    

    ② 再次运行 npm run dev 命令,重新进行项目的打包
    ③ 在浏览器中访问 http://localhost:8080/src 地址,查看自动打包效果
    此时再次修改index.js代码,则会自动重新打包,且页面会即时改变

    为何/ok.js不是/disk/ok.js引用打包文件?

    webpack-dev-server 生成到内存中的文件,默认放到了项目的根目录中,而且是虚拟的、不可见的。
    ⚫ 可以直接用/表示项目根目录,后面跟上要访问的文件名称,即可访问内存中的文件
    ⚫ 例如 /bundle.js 就表示要访问 webpack-dev-server 生成到内存中的 bundle.js 文件

    二、html-webpack-plugin

    上一步要访问index.html要先进入src下才行,为了自动访问可以使用html-webpack-plugin插件解决
    它的原理是把index.html复制一份到根目录(同样是在内存中实际不可见)

    1安装插件

    npm install html-webpack-plugin -D

    2 配置 html-webpack-plugin

    //【1】
    const HtmlPlugin=require('html-webpack-plugin')
    //【2】
    const htmlPlugin=new HtmlPlugin({
        template:'./src/index.html',
        filename:'./index.html'
    })
    
    
    module.exports={
        mode:'development',
        entry:path.join(__dirname,'./src/index.js'),
        output:{
            path:path.join(__dirname,'./dist/'),
            filename:'main.js'
        },
        //【3】
        plugins:[htmlPlugin]    
    }
    

    重启项目,再访问就可直接看到页面
    http://localhost:8080/
    此外如果./src/index.html不引入main.js该插件也会复制到根目录同时自动引入此js

  • 相关阅读:
    cmd 新建安卓工程
    新创建的android工程里面没有activity问题解决
    背景色横向渐变css5
    Serialable与Parcelable
    Observer观察者模式
    Linux基础(1)
    android 出现Make sure the Cursor is initialized correctly before accessing data from it
    android项目中导入actionbarsherlock 需要注意的地方
    android BadgeView的使用(图片上的文字提醒)
    android仿系统Launcher界面,实现分屏,左右滑动效果(ViewSwitcher)
  • 原文地址:https://www.cnblogs.com/chenxi188/p/16007262.html
Copyright © 2020-2023  润新知