天天看點

webpack-輸出

1.環境準備和指令

npm init -y
npm install --save-dev webpack
npm install --save-dev webpack-cli
npm install --save lodash
npm run build
           

2.目錄

webpack-輸出

3.代碼檔案 

dist/index.html

<!doctype html>
<html>
  <head>
    <title>Asset Management</title>
    <script src="./print.bundle.js"></script>
  </head>
  <body>
    <script src="./app.bundle.js"></script>
  </body>
</html>
           

src/index.js 

import _ from 'lodash';
import printMe from './print.js';

function component() {
  var element = document.createElement('div');
  var btn = document.createElement('button');

  // Lodash(目前通過一個 script 腳本引入)對于執行這一行是必需的
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  btn.innerHTML = 'Click me and check the console!';
  btn.onclick = printMe;
  element.appendChild(btn);

  return element;
}

document.body.appendChild(component());
           

 src/print.js

export default function printMe() {
    //console.log('I get called from print.js!');
    alert('I get called from print.js!');
  }
           

 package.json

{
  "name": "webpack-out",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "lodash": "^4.17.15"
  }
}
           

 webpack.config.js

const path = require('path');

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

4.運作效果

webpack-輸出

5.代碼分析

webpack-輸出