Webpack入门(一)

泪湿孤枕 提交于 2020-01-22 23:57:25

安装webpack

npm install webpack//安装webpack
npm install --save-dev webpack//在项目中安装webpack
npm init //创建package.json文件

配置

//package.json
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server",
    "build": "webpack"
  },

使用yarn:
yarn init -y
yarn add webpack webpack-cli -d//-d是开发环境配置打包后没有
npx webpack//打包后dist文件夹里形成app.js
yarn add webpack-dev-server -d//安装运行工具

不使用yarn:
npm i webpack-cli -g//全局安装
或者npm install webpack-cli --save-dev//正常安装
webpack hello.js -o hello.bundle.js//终端打包

运行

npm run dev (开发环境输出的demo.js没有压缩);
npm run build (生产模式输出的demo.js压缩过);

webpack中clean-webpack-plugin插件使用遇到的问题及解决方法

在这里插入图片描述

配置相关

1. 加载CSS
npm install --save-dev style-loader css-loader
// webpack.config.js
  const path = require('path');

  module.exports = {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    },
+   module: {
+     rules: [
+       {
+         test: /\.css$/,
+         use: [
+           'style-loader',
+           'css-loader'
+         ]
+       }
+     ]
+   }
  };
2. 加载图片
npm install --save-dev file-loader
//webpack.config.js
  const path = require('path');

  module.exports = {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            'css-loader'
          ]
        },
+       {
+         test: /\.(png|svg|jpg|gif)$/,
+         use: [
+           'file-loader'
+         ]
+       }
      ]
    }
  };

3. 构建本地服务器
npm install --save-dev webpack-dev-server
//webpack.config.js
const path = require('path');

module.exports = {
    entry: './src/index.js',  //表示要打包的文件
    output: {...
    },
    module: {...
    },
+    devServer: {
+        port: 8080,
+        hot: true
+    }
}

//package.json
 {
    "name": "webpack-demo",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
+     "start":"webpack-dev-server --open"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
      "webpack": "^4.0.1",
      "webpack-cli": "^2.0.9",
      "lodash": "^4.17.5"
    }
  }


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!