webpack 4.x版本手动配置

  • 运行 npm init -y 快速初始化项目

  • 在项目根目录创建src源代码目录和dist产品目录

  • 在src目录下创建 index.html

    • mani.js文件如果后期使用entry打包,这里可以手动创建
  • 使用npm 安装webpack, 运行npm i webpack/webpack-cli -D

    • 全局运行npm i cnpm -g
  • 手动创建webpack.config.js文件

  • 注意:webpack4.x 提供了约定大于配置的概念:目的是为了尽量减少配置文件的体积;

    • 默认约定了
    • 打包的入口是src>index.js
    • 打包的输出文件是 dist>main.js
    • 4.x中新增了mode选项(必选项),可选值为:development和production;
  • 或者在webpack.config.js中配置 entry

     module.exports={
            mode:'development' // development production
            
        }
    

    实时打包模块

  • 安装
  •  npm install webpack-dev-server -D
    
  • package.json中设置dev
     "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1",
            "dev":"webpack-dev-server"
    

      

  • 启动dev运行
    npm run dev
     webpack-dev-server 打包好的main.js是托管到了内存中;所以在项目根目录中看不到;但是我们可以认为,在项目根目录中,有一个看不见的main.js
  • index.js中引入根目录main.js
    <script src="/main.js"></script>
    
  • package.json中设置dev属性

    • --open 自动打开浏览器 后面可以添加 iexplore chrom ....浏览器
    • --port 3000 : 执行端口号为3000
    • --hot :
    • --progress :打包进度
    • --compress : 压缩
    • --host 127.0.0.1 : 执行域名
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev":"webpack-dev-server --open --port 3000 --hot"
    },

自动打开index.html 首页模块

  • 安装模块
    npm install html-webpack-plugin -D
  • webpack.config.js中配置
 const path=require('path');
  const HtmlWebPackPlugin=require('html-webpack-plugin') // 导入 在内存中自动生成index页面的插件

// 创建一个插件的实例对象
const htmlPlugin=new HtmlWebPackPlugin({
template: path.join(__dirname,'./src/index.html'), // 源文件
 filename:'index.html' // 生成的内存中首页的名称
})

// 加入模块
module.exports={
    mode:'development',
    plugins:[
    htmlPlugin
    ]
}

  

将index中<script src="/main.js"></script>去掉,让他自己打包执行

posted @ 2020-07-27 17:19  红妆  阅读(187)  评论(0编辑  收藏  举报