webpack 学习-从 helloworld 开始

112 阅读1分钟

从 helloworld 开始

  1. 初始化目录
npm init
// 接着一直回车
  1. 安装 webpack
npm install webpack --save-dev
  1. 安装 webpack-cli
npm install webpack-cli --save-dev
  1. 创建以下目录,并添加内容
│  index.html // 模板文件
│
├─config
│       webpack.config.js // webpack 配置
│
└─src
        index.js // 打包的文件

index.HTML

<!doctype html>
<html>

    <head>
        <title>webpack</title>
    </head>
    
    <body>
        <script src="dist/bundle.js"></script>
    </body>

</html>

webpack.config.js

const path = require('path');

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

index.js

console.log("loaded")
document.getElementsByTagName('body')[0].innerHTML='helloword'
  1. 添加启动命令 在 package.json 的 scripts 中添加:
"build": "webpack --config config/webpack.config.js --mode production"
  1. 启动
npm run build
  1. 双击 index.html 用浏览器打开,看到 helloword
  2. DONE