用webpack3和webpack-dev-server编写页面

首先是怎么用webpack搭建一个项目

命令行运行
npm install webpack -g

接着
npm init
npm install --save-dev webpack
在项目文件夹下新建一个webpack.config.js,现在弄个小的例子:
module.exports = {
  entry:  __dirname + "/app/main.js",//已多次提及的唯一入口文件
  output: {
    path: __dirname + "/public",//打包后的文件存放的地方
    filename: "bundle.js"//打包后输出文件的文件名
  }
}
这样可以新建两个js文件,你们可以线下演示。

接着我们说一下loader

npm install --save-dev babel-core babel-loader babel-preset-env css-loader html-loader url-loader --save-dev
这里提一下,我怕有些不学习只会问的认不懂为什么要在在--save后面加-dev,加-dev是标明在开发环境要用到的插件,项目上线就不会用到。
babel-corebabel-loaderbabel-preset-env
babel-preset-env是用来把es6语法转换成es6语法,很多webpack打包出错都是因为没有把es6的代码转换成es5的。当然如果你的代码不是要压缩的自然不会报错。
{
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ["env"]
                }
            },
还有一点 babel-preset-env的原身是babel-preset-es2015,而现在和未来babel-preset-es2015真的要告别世界了。
css-loader
webpack提供两个工具处理样式表, css-loader style-loader ,二者处理的任务不同, css-loader 使你能够使用类似 @import url(...) 的方法实现 require() 的功能, style-loader 将所有的计算后的样式加入页面中,二者组合在一起使你能够把样式表嵌入webpack打包后的JS文件中。
如果不用css单独打包,则可以这样写:
module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    {
                        loader: "style-loader"
                    }, {
                        loader: "css-loader"
                    }
                ]
            }
        ]
    }
而如果你需要css单独打包,这就要用到extract-text-webpack-plugin这个插件
var ExtractTextPlugin   = require('extract-text-webpack-plugin');
{ 
            	test: /\.css$/,
            	loader: ExtractTextPlugin.extract("style-loader","css-loader") 
  },
在代码打包过程中如果css报错,有可能是你的style-loader和css-loader位置写错,兑换回来就可以了。

html-loader 在webpack官网上说的一大堆,反正我是看不懂,不过有一段是值得注意的

一个很常见的场景,将 HTML 导出到 .html 文件中,直接访问它们,而不是使用 javascript 注入。这句话的意思就是把html文件当成组件那些导入到html文件中,比如头部和底部文件,这样可以很大程度的节省我们开发的时间。


{ 
            	test: /\.string$/,
            	loader: 'html-loader'
 }
这里写的是string后缀而不是html后缀是因为我后面用到一个html-webpack-plugin插件,html代码这样写

在index.html中:
<body>
        <%= require('html-loader!./layout/nav.html')  %>
</body>
剩下的其他loader可以去官网查看
接着是别名配置:
resolve : {
        alias : {
            node_modules    : __dirname + '/node_modules',
            util            : __dirname + '/src/util',
            page            : __dirname + '/src/page',
            service         : __dirname + '/src/service',
            image           : __dirname + '/src/image'
        }
    },

plugins

这里只讲三个插件,一个需要用到webpack自带的插件webpack.optimize.CommonsChunkPlugin
var webpack             = require('webpack');
 new webpack.optimize.CommonsChunkPlugin({
            name : 'common',
            filename : 'js/base.js'
        }),
这个是用来把通用的js文件打包到base.js中

html-webpack-plugin
这个是html模板的处理,当然里面的配置很多

  • title: The title to use for the generated HTML document.
  • filename: The file to write the HTML to. Defaults to index.html. You can specify a subdirectory here too (eg: assets/admin.html).
  • template: Webpack require path to the template. Please see the docs for details.
  • injecttrue | 'head' | 'body' | false Inject all assets into the given template or templateContent - When passing true or 'body' all javascript resources will be placed at the bottom of the body element. 'head' will place the scripts in the head element.
  • favicon: Adds the given favicon path to the output html.
  • minify{...} | false Pass html-minifier's options as object to minify the output.
  • hashtrue | false if true then append a unique webpack compilation hash to all included scripts and CSS files. This is useful for cache busting.
  • cachetrue | false if true (default) try to emit the file only if it was changed.
  • showErrorstrue | false if true (default) errors details will be written into the HTML page.
  • chunks: Allows you to add only some chunks (e.g. only the unit-test chunk)
  • chunksSortMode: Allows to control how chunks should be sorted before they are included to the html. Allowed values: 'none' | 'auto' | 'dependency' |'manual' | {function} - default: 'auto'
  • excludeChunks: Allows you to skip some chunks (e.g. don't add the unit-test chunk)
  • xhtmltrue | false If true render the link tags as self-closing, XHTML compliant. Default is false
这一串都是英文我就没办法翻译了,现在我把我用刀的列出来
var getHtmlConfig = function(name, title){
    return {
        template    : './src/view/' + name + '.html',
        filename    : 'view/' + name + '.html',
        title       : title,
        inject      : true,
        hash        : true,
        chunks      : ['common', name]
};
};
template是开发环境时html文件的目录,filename是要输出的目录,title就是页面的标题,当然在html文件里要这样配

<title><%= htmlWebpackPlugin.options.title%> </title>
如果要配 favicon需要加

favicon     : './src/image/favicon.ico',
现在把webpack.config.js文件列出来

var webpack             = require('webpack');
var ExtractTextPlugin   = require('extract-text-webpack-plugin');
var HtmlWebpackPlugin   = require('html-webpack-plugin');

// 环境变量配置,dev / online
var WEBPACK_ENV         = process.env.WEBPACK_ENV || 'dev';

// 获取html-webpack-plugin参数的方法 
var getHtmlConfig = function(name, title){
    return {
        template    : './src/view/' + name + '.html',
        filename    : 'view/' + name + '.html',
        title       : title,
        inject      : true,
        hash        : true,
        chunks      : ['common', name]
    };
};
// webpack config
var config = {
    entry: {
        'common'            : ['./src/page/common/index.js'],
        'index'             : ['./src/page/index/index.js'],
        'list'              : ['./src/page/list/index.js'],
        'detail'            : ['./src/page/detail/index.js'],
        'cart'              : ['./src/page/cart/index.js'],
        'user-login'        : ['./src/page/user-login/index.js'],
        'user-register'     : ['./src/page/user-register/index.js'],
        'user-pass-reset'   : ['./src/page/user-pass-reset/index.js'],
        'user-center'       : ['./src/page/user-center/index.js'],
        'user-center-update': ['./src/page/user-center-update/index.js'],
        'user-pass-update'  : ['./src/page/user-pass-update/index.js'],
        'result'            : ['./src/page/result/index.js'],
    },
    output: {
        path: './dist',
        publicPath : '/dist',
        filename: 'js/[name].js'
    },
    externals : {
        'jquery' : 'window.jQuery'
    },
    module: {
        loaders: [
            { 
            	test: /\.css$/,
            	loader: ExtractTextPlugin.extract("style-loader","css-loader") 
            },
            { test: /\.(gif|png|jpg|woff|svg|eot|ttf)\??.*$/, loader: 'url-loader?limit=100&name=resource/[name].[ext]' },
            { 
            	test: /\.string$/,
            	loader: 'html-loader'
            	}
        ]
    },
    resolve : {
        alias : {
            node_modules    : __dirname + '/node_modules',
            util            : __dirname + '/src/util',
            page            : __dirname + '/src/page',
            service         : __dirname + '/src/service',
            image           : __dirname + '/src/image'
        }
    },
    plugins: [
        // 独立通用模块到js/base.js
        new webpack.optimize.CommonsChunkPlugin({
            name : 'common',
            filename : 'js/base.js'
        }),
        // 把css单独打包到文件里
        new ExtractTextPlugin("css/[name].css"),
        // html模板的处理
        new HtmlWebpackPlugin(getHtmlConfig('index', '首页')),
        new HtmlWebpackPlugin(getHtmlConfig('list', '商品列表页')),
        new HtmlWebpackPlugin(getHtmlConfig('detail', '商品详情页')),
        new HtmlWebpackPlugin(getHtmlConfig('cart', '购物车')),
        new HtmlWebpackPlugin(getHtmlConfig('user-login', '用户登录')),
        new HtmlWebpackPlugin(getHtmlConfig('user-register', '用户注册')),
        new HtmlWebpackPlugin(getHtmlConfig('user-pass-reset', '找回密码')),
        new HtmlWebpackPlugin(getHtmlConfig('user-center', '个人中心')),
        new HtmlWebpackPlugin(getHtmlConfig('user-center-update', '修改个人信息')),
        new HtmlWebpackPlugin(getHtmlConfig('user-pass-update', '修改密码')),
        new HtmlWebpackPlugin(getHtmlConfig('result', '操作结果')),
    ]
};

if('dev' === WEBPACK_ENV){
    config.entry.common.push('webpack-dev-server/client?http://localhost:8088/');
}

module.exports = config;
package.json如下
{
  "name": "webpack",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "set WEBPACK_ENV=dev && webpack-dev-server --inline --port 7071",
    "dev-linux": "WEBPACK_ENV=dev webpack-dev-server --inline --port 7071",
    "build": "set WEBPACK_ENV=online && webpack -p",
    "build-linux":"WEBPACK_ENV=online webpack -p"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1",
    "babel-runtime": "^6.26.0",
    "css-loader": "^0.28.9",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.6",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^2.30.1",
    "style-loader": "^0.20.1",
    "url-loader": "^0.6.2",
    "webpack": "^3.10.0",
    "webpack-dev-server": "^2.11.1"
  }
}
在项目搭建环境过程中,如果报错,首先要看是否是插件或者loader和webpack版本不兼容。
项目过程中,我用到跨域,所以要配一个跨域
devServer:{
        proxy: {
            '*': {
                target: 'http://localhost:7070',
                changeOrigin: true,
                secure: false,
                ws: false,
            }
        }
    },
代码中有个这样的代码
 externals : {
        'jquery' : 'window.jQuery'
    },
这个是设置jquery可以被识别。

在package中有以下几个配置
"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "set WEBPACK_ENV=dev && webpack-dev-server --inline --port 7071",
    "dev-linux": "WEBPACK_ENV=dev webpack-dev-server --inline --port 7071",
    "build": "set WEBPACK_ENV=online && webpack -p",
    "build-linux":"WEBPACK_ENV=online webpack -p"
  },
第一个配置不用理,去掉也可以,凡是带-linux都是在linux系统和ios系统运行的,如果在linux中运行,需要在项目目录中新建一个.babelrc文件,记住了,这个是.开头的文件在window下肯定不能新建,需要linux命令行,具体linux新建文件的命令自己去百度。
新建的.babelrc文件代码如下
{
 "presets": [
        ["env", { "modules": false }]
    ]
}
在linux系统进行代码压缩的时候报了一个os系统的警告,查了官方的说明,官方说这句话没影响,可以不理。
dev 是开发环境命令,命令行运行npm run dev,我怕真有认不懂怎么运行,那你们真的可以换工作了。
build是代码打包上线,webpack如果不加- p表示代码不压缩。
这里用到了webpack-dev-server,这个是用来开发项目的服务,页面热刷新,这样可以节省我们很多的时间。
当然,当你打开页面的时候会出现这个页面,页面下会有你当前目录的文件列表,所以你要点的是dist目录下的文件,而不是src下的view文件夹。
比如我要在浏览器打开index页面,url地址就是http://localhost:7071/dist/view/index.html,而不是http://localhost:7071/src/view/index.html,否则你用到 <%= require('html-loader!./layout/head.html')%>就会报错。
当然,页面开发过程中,遇到最多的报错就是img的路径,在头部组件用到的img路径我是这样写
 <img src="../../image/index/logo.png" alt="">
路径相对于你存放头部组件的位置。在index里img的路径这样写
 <img src="<%= require('../image/index/investment.png')%>" alt="">
路径相对于你存放index的位置。我的文件目录结构如下:


猜你喜欢

转载自blog.csdn.net/oumaharuki/article/details/79272274