用webpack打包JS文件

命令行用webpack命令打包单个JS文件

set path=%path%;
webstorm64 ./

cnpm init //产生package.json文件

cnpm install webpack webpack-cli --save-dev //安装依赖
–save-dev: 依赖包定义在dependencies中
–save:依赖包定义在devDependencies中

cnpm install:安装package.json中dependencies和devDependencies中的依赖
cnpm install -production:安装dependencies中的依赖

cnpm install css-loader style-loader --save-dev
webpack hello.js -o hello.bundle.js //打包

//处理css文件
webpack hello.js hello.bundle.js --module-bind ‘css=style-loader!css-loader’

//自动打包
webpack hello.js hello.bundle.js --module-bind ‘css=style-loader!css-loader’ --watch
//查看打包过程
webpack hello.js hello.bundle.js --module-bind ‘css=style-loader!css-loader’ --progress
//显示打包模块
webpack hello.js hello.bundle.js --module-bind ‘css=style-loader!css-loader’ --display-modules
//显示打包模块的原因
webpack hello.js hello.bundle.js --module-bind ‘css=style-loader!css-loader’ --display-modules --display-reasons

//指定非默认配置文件名:webpack --config webpack.dev.config.js
webpack --config webpack.config.js --progress --display-modules --colors --display-reasons

cnpm run webpack //运行名为webpack的脚本文件,此脚本文件在package.json中定义

webpack.config.js文件如下:

module.exports={
    entry: "./src/script/main.js",
    output:{
        path:__dirname+'/dist/js/',
        filename:'bundle.js'
    }
}

生成HTML页面文件

cnpm install html-webpack-plugin --save-dev

windows系统的文件夹名出现以点结尾,说明系统有非原生的内核执行过命令,在Windows系统中删不掉。

webpack.config.js文件如下:


var htmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
    entry:{
        main:"./src/script/main.js",
        a:"./src/script/a.js"
    },
    output:{
        path:__dirname+'/dist',
        filename:'js/[name]-[chunkhash].js',
        publicPath: "http://cdn.webpack/"
    },
    plugins: [
        new htmlWebpackPlugin({
            template: "index.html",
            inject: false,
            filename: "index.html",
            title:"webpack is good",
            date:new Date(),
            minify: {
                removeComments:true,
                collapseWhitespace:true
            }
        })
    ]
}

同一页面使用不同JS

webpack.config.js文件如下:

var htmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
    entry:{
        main:"./src/script/main.js",
        a:"./src/script/a.js",
        b:"./src/script/b.js",
        c:"./src/script/c.js"
    },
    output:{
        path:__dirname+'/dist',
        filename:'js/[name]-[chunkhash].js',
    },
    plugins: [
        new htmlWebpackPlugin({
            template: "index.html",
            inject: "head",
            filename: "a.html",
            title:"this is a.html",
            chunks: ['main','a']
        }),
        new htmlWebpackPlugin({
            template: "index.html",
            inject: "head",
            filename: "b.html",
            title:"this is b.html",
            chunks: ['b']
        }),
        new htmlWebpackPlugin({
            template: "index.html",
            inject: "head",
            filename: "c.html",
            title:"this is c.html",
            chunks: ['c']
        })

    ]
}

同一页面使用不同JS,JS的公共部分用inline注入

webpack.config.js文件如下:

var htmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
    entry:{
        main:"./src/script/main.js",
        a:"./src/script/a.js",
        b:"./src/script/b.js",
        c:"./src/script/c.js"
    },
    output:{
        path:__dirname+'/dist',
        filename:'js/[name]-[chunkhash].js',
    },
    plugins: [
        new htmlWebpackPlugin({
            template: "index.html",
            inject: false,
            filename: "a.html",
            title:"this is a.html",
            chunks: ['main','a']
        }),
        new htmlWebpackPlugin({
            template: "index.html",
            inject: false,
            filename: "b.html",
            title:"this is b.html",
            chunks: ['main','b']
        }),
        new htmlWebpackPlugin({
            template: "index.html",
            inject: false,
            filename: "c.html",
            title:"this is c.html",
            chunks: ['main','c']
        })
    ]
}

模板index.html如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
    <script type="text/javascript">
        <%= compilation.assets[htmlWebpackPlugin.files.chunks.main.entry.substr
        (htmlWebpackPlugin.files.publicPath.length)].source() %>
    </script>
</head>
<body>
<% for(var key in htmlWebpackPlugin.files.chunks){ %>
    <% if(key !== 'main'){%>
        <script src="<%=htmlWebpackPlugin.files.chunks[key].entry%>" type="text/javascript"></script>
    <% }%>
<% } %>
</body>
</html>

用babel转换ES6代码,打包生成JS代码

webpack.config.js文件如下:

var htmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
    entry:"./src/app.js",
    output:{
        path:__dirname+'/dist',
        filename:'js/[name].bundle.js',
    },
    module:{
      rules:  [
          {
              test:/\.js$/,
              include:__dirname+'/src',
              exclude:__dirname+'/node_modules',
              use:{
                  loader: "babel-loader",
                  options: {
                      presets:["latest"]
                  }
              }
          }
      ]
    },
    plugins: [
        new htmlWebpackPlugin({
            template: "index.html",
            inject: "body",
            filename: "index.html",
        })
    ]
}

app.js文件如下:

import layer from "./components/layer/layer.js"

const App = function () {
  const num=1;
  alert(num);
  console.log(layer);
};

new App();

目标index.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Webpack App</title>
</head>
<body>
<script type="text/javascript" src="js/main.bundle.js"></script></body>
</html>

package.json文件如下:注意依赖包的版本,版本的差异会导致代码的差异。

{
  "name": "webpackdemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "webpack": "webpack --config webpack.config.js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.7.7",
    "babel-core": "^6.26.3",
    "babel-loader": "^8.0.6",
    "babel-preset-latest": "^6.24.1",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.41.5",
    "webpack-cli": "^3.3.10"
  }
}

处理CSS

安装
“style-loader”: “^1.1.2”,
“css-loader”: “^3.4.1”,
“postcss-loader”: “^3.0.0”,
“autoprefixer”: “^9.7.3”, //自动补齐浏览器前缀

webpack.config.js文件如下:

var htmlWebpackPlugin=require('html-webpack-plugin');
module.exports={
    entry:"./src/app.js",
    output:{
        path:__dirname+'/dist',
        filename:'js/[name].bundle.js',
    },
    module:{
      rules:  [
          {
              test:/\.js$/,
              include:__dirname+'/src',
              exclude:__dirname+'/node_modules',
              use:{
                  loader: "babel-loader",
                  options: {
                      presets:["latest"]
                  }
              }
          },
          {
              test:/\.css$/,
              exclude:__dirname+'/node_modules',
              use:[
                  {
                      loader: "style-loader"
                  },
                  {
                      loader: "css-loader",
                      options: {
                          importLoaders:1
                      }
                  },
                  {
                      loader: "postcss-loader"
                  }
              ]
          }
      ]
    },
    plugins: [
        new htmlWebpackPlugin({
            template: "index.html",
            inject: "body",
            filename: "index.html",
        })
    ]
}

postcss.config.js文件如下:

module.exports = {
    plugins: [
        require('autoprefixer')({
        })
    ]
}

CSS文件中引入其他CSS文件:@import “XXX.css”;
importLoaders:1 //解决多级引用的样式处理

模板文件处理

安装html-loader依赖,当前导入的html文件是字符串的形式。

index.html文件如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div id="app"></div>
</body>
</html>

main.js文件如下:

import './css/common.css';
import Layer from "./components/layer/layer.js";

const App = function () {
    var app=document.getElementById("app");
    var tpl= new Layer();
    app.innerHTML=tpl.tpl;
};

new App();

layer.js文件如下:

import tpl from "./layer.html";

function layer() {
    return{
        name:'layer',
        tpl:tpl
    };
}

export default layer;

layer.html文件如下:

<div class="layer">
    <div>this is a layer.</div>
</div>

处理项目中的资源文件

安装对应的加载器,比如file-loader,配置webpack.config.js,就能够解析资源文件。参考官网https://www.npmjs.com/

发布了10 篇原创文章 · 获赞 1 · 访问量 2318

猜你喜欢

转载自blog.csdn.net/qq_35334269/article/details/103849439