webpack 前端構建

1、創建簡單的項目目錄

一、建立 manager 根目錄(做爲項目根目錄)
二、執行 npm init,在根目錄manager下自動生成 package.json文件
三、npm install webpack --save-dev,在項目中安裝 webpack npm包
四、在根目錄下 建立 webpack.config.js,全部的配置代碼都寫在裏面
五、在根目錄建立 src 目錄,包含 html目錄 > index.html,css目錄 > index.css,js目錄 > index.js,images目錄 > index...javascript

如圖:css

 

2、配置webpack.config.js文件

一、簡單配置及使用html

module.exports = {
    entry: {
        'js/index': './src/js/index.js'
    },
    output: {
        path: './build',
        filename: '[name].js'
    }
};

執行構建命令:./node_modules/webpack/bin/webpack.jsjava

ok,生成下圖的目錄結構了node

 

二、安裝,使用html-webpack-plugin插件webpack

上一步咱們經過構建,在根目錄下生成了 ./build/js/index.js 文件,咱們但願 生成 ./build/html/index.html 文件
首先安裝一下插件 npm install html-webpack-plugin --save-dev,再來看看咱們的配置代碼es6

var HtmlWebpackPlugin = require('html-webpack-plugin');
var plugins = [];

plugins.push(
    new HtmlWebpackPlugin({
        template: './src/html/index.html',
        filename: 'html/index.html',
        inject: 'body',
        hash: true, // index.js?hash
        cache: true, // if true (default) try to emit the file only if it was changed.
        showErrors: true, // if true (default) errors details will be written into the html page.
        chunks: ['js/index'] // filter chunks
    })
);

module.exports = {
    entry: {
        'js/index': './src/js/index.js'
    },
    output: {
        path: './build',
        filename: '[name].js'
    },
    plugins: plugins
};

執行構建命令:./node_modules/webpack/bin/webpack.js後web

打開./build/html/index.html文件,發現html中自動加上了script標籤,引用的js路徑加上了hash值,是否是感受很贊
<script type="text/javascript" src="../js/index.js?f5f204be195973d9d81c"></script>npm

構建後的項目目錄如圖:json

 

三、配合babel編譯器,讓咱們所寫的js代碼支持es6語法

babel官網地址:https://babeljs.io/

安裝babel編譯器
npm install --save-dev babel-loader babel-core
npm install --save-dev babel-preset-es2015

在根目錄下建立 .babelrc 配置文件

{
  "presets": ["es2015"]
}

webpack.config.js配置以下:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var plugins = [];
var loaders = [
   { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
   { test: /\.css$/, loader: "style-loader!css-loader" }
];

plugins.push(
    new HtmlWebpackPlugin({
        template: './src/html/index.html',
        filename: 'html/index.html',
        inject: 'body',
        hash: true, // index.js?hash
        cache: true, // if true (default) try to emit the file only if it was changed.
        showErrors: true, // if true (default) errors details will be written into the html page.
        chunks: ['js/index'] // filter chunks
    })
);

module.exports = {
    entry: {
        'js/index': './src/js/index.js'
    },
    output: {
        path: './build',
        filename: '[name].js'
    },
    module: {
        loaders: loaders
    },
    plugins: plugins
};

準備好了,咱們在 ./src/js/index.js文件中寫入:

function testEs6(a, ...args) {
    console.log(args); // [2,3,4]
}

testEs6(1,2,3,4);

console.log(Set);
console.log(Map);

new Promise(function(resolve, reject) {});

執行構建命令:./node_modules/webpack/bin/webpack.js,OK,編譯成功了,並無報錯,這意味着你能夠在你的項目中使用es6了

 

四、css文件能夠做爲模塊在js中被引入

npm install css-loader --save-dev
npm install style-loader --save-dev

在webpack.config.js文件中配置

var loaders = [
   { test: /\.css$/, loader: "style-loader!css-loader" }
];

在./src/js/index.js中 引入css文件

require('../css/index.css');

執行構建命令:./node_modules/webpack/bin/webpack.js,能夠看到 ./src/css/index.css中的css代碼 放在了./build/html/index.html文件的style標籤內

 

五、本地服務 webpack-dev-server

npm install --save-dev webpack-dev-server

執行服務啓動命令:./node_modules/.bin/webpack-dev-server --progress --host 0.0.0.0 --port 8080 --colors --inline --hot --display-error-details --content-base src/

你能夠經過瀏覽器輸入下面地址來訪問你的項目:
http://0.0.0.0:8080/html
localhost:8080/html
你的ip:8080/html

ok,也能夠經過配置 webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin');
var plugins = [];
var loaders = [
   { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
   { test: /\.css$/, loader: "style-loader!css-loader" }
];

plugins.push(
    new HtmlWebpackPlugin({
        template: './src/html/index.html',
        filename: 'html/index.html',
        inject: 'body',
        hash: true,
        cache: true,
        showErrors: true,
        chunks: ['js/index']
    })
);

module.exports = {
    entry: {
        'js/index': './src/js/index.js'
    },
    output: {
        path: './build',
        filename: '[name].js'
    },
    devServer: {
        progress: true,
        host: '0.0.0.0',
        port: 8080,
        colors: true,
        inline: true,
        // hot: true,
        contentBase: './src',
        displayErrorDetails: true
    },
    module: {
        loaders: loaders
    },
    plugins: plugins
};

配置完了後,咱們 在執行命令 ./node_modules/.bin/webpack-dev-server,ok,成功了
咱們隨便修改一下 ./src/html/index.html代碼(也能夠修改css,js代碼),瀏覽器頁面將會自動刷新,實時預覽,神奇吧....

六、多文件自動構建

// webpack.config.js

var glob = require('glob');
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var source = getSource();

var loaders = [
   { test: /\.js$/, exclude: /node_modules/, loader: "babel-loader" },
   { test: /\.css$/, loader: "style-loader!css-loader" }
];

var plugins = (function() {
    var arr = [];

    source.htmlFiles.forEach(function(htmlFile) {
        arr.push(
            new HtmlWebpackPlugin({
                template: htmlFile.pageSource,
                filename: htmlFile.filename,
                inject: 'body',
                hash: true,
                cache: true,
                showErrors: true,
                chunks: [htmlFile.jsChunkName]
            })
        );
    });

    return arr;
}());

module.exports = {
    entry: source.entry,
    output: {
        path: './build',
        filename: '[name].js'
    },
    devServer: {
        progress: true,
        host: '0.0.0.0',
        port: 8080,
        colors: true,
        inline: true,
        hot: true,
        contentBase: './src',
        displayErrorDetails: true
    },
    module: {
        loaders: loaders
    },
    plugins: plugins
};

function getSource() {
    var source = {
        htmlFiles: [],
        entry: {}
    };

    var pageSource = glob.sync('./src/html/*.html');
    var jsSource = glob.sync('./src/js/**/*.js');
    var entry = {}; // 存儲 all

    jsSource.forEach(function(item) {
        entry['js/' + path.basename(item, '.js')] = item;
    });

    pageSource.forEach(function(page) {
        var jsChunkName = 'js/' + path.basename(page, '.html');
        source.htmlFiles.push({
            filename: 'html/' + path.basename(page),
            pageSource: page,
            jsChunkName: jsChunkName
        });

        source.entry[jsChunkName] = entry[jsChunkName];
    });

    return source;
}

ps:轉載請註明出處:楊君華

相關文章
相關標籤/搜索