Webpack - 基础设置

一:基础设置
参考:https://webpack.js.org/guides/getting-started/
npm init -y
npm install webpack webpack-cli --save-dev
代码:
webpack.config.js

const path = require(‘path‘);

module.exports = {
  entry: ‘./src/index.js‘,
  output: {
    filename: ‘main.js‘,
    path: path.resolve(__dirname, ‘dist‘),
  },
};

package.json

{
  "name": "sample-1",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.25.0",
    "webpack-cli": "^4.5.0"
  }
}

Src/index.js

function component() {
    const element = document.createElement(‘div‘);
  
    // Lodash, currently included via a script, is required for this line to work
    element.innerHTML = ‘hello, world!‘; //_.join([‘Hello‘, ‘webpack‘], ‘ ‘);
  
    return element;
  }
  
  document.body.appendChild(component());

dist/index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Getting Started</title>
    <script src="https://unpkg.com/lodash@4.17.20"></script>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

最后:npm run build

二:加载CSS
npm install --save-dev style-loader css-loader
webpack.config.js加入以下配置

  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [‘style-loader‘, ‘css-loader‘],
      },
    ],
  },

Webpack - 基础设置

增加src/style.css

.hello {
    color: red;
  }

Index.js增加以下代码

import ‘./style.css‘;
element.classList.add(‘hello‘);

三:加载图片
Webpack.config.js -> Module节点加入以下代码

      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: ‘asset/resource‘,
      }

Src -> 添加logo.png
Index.js 添加

    const myIcon = new Image();
    myIcon.src = Icon;
    element.appendChild(myIcon);

style.css 添加

background: url(‘./logo.png‘);

最后npm run build

Webpack - 基础设置

上一篇:前端面试题(HTML和css部分)


下一篇:LNMP搭建静态网页服务器