1. 程式人生 > >webpack入門第6篇

webpack入門第6篇

今天開始的是我看過的視訊,學習其他資料學到的。在這裡分享一下,希望對看到這篇部落格的有些幫助
1,新建資料夾demo4,在demo4裡,彈出命令列,輸入

npm init

執行結果如下:

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on
these fields
and exactly what they do. Use `npm install <pkg> --save` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. name: (demo4) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC) About to
write to E:\學習\前端\webpack\new\study\demo4\package.json: { "name": "demo4", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC" } Is this ok? (yes)

2、執行命令,新增webpack的loader

npm install css-loader style-loader -D

3,新建幾個檔案,
index.html

<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<script type="text/javascript" src="bundle.js" charset="utf-8"></script>
</body>
</html>

content.js

/**
 * Created by Administrator on 2017/9/20.
 */
module.exports = "It works from content.js.";

entry.js

/**
 * Created by Administrator on 2017/9/20.
 */
require("./style.css");
document.write(require("./content.js"));

style.css

body {
    background: green;
}

webpack.config.js

module.exports = {
    entry: "./entry.js",
    output: {
        path: __dirname,
        filename: "bundle.js"
    },
    module: {
        loaders: [
            { test: /\.css$/, loader: "style-loader!css-loader" }
        ]
    }
};

注意,最新版本不支援簡寫了,要輸全了,可能是為了規範吧。,如下寫法:

loader: "style-loader!css-loader"

5、現在是執行webpack的命令時候了,在命令列輸入

webpack

6、執行index.html檢視結果。


下面一起學習一下,如何用npm start啟動,很簡單,修改package.json,在scripts裡新增

  "scripts": {
    "start":"webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

然後在命令列輸入

npm start

成功了,執行index.html檢視結果。
那麼我們再試試,如何實時監控頁面,不用再重新編譯了,
修改scripts,如下

"scripts": {
    "start":"webpack --progress --colors --watch",
    "test": "echo \"Error: no test specified\" && exit 1"
  },

在命令列輸入

npm start

好了,我們又一次成功了。執行index.html檢視結果吧。