今天开始的是我看过的视频,学习其他资料学到的。在这里分享一下,希望对看到这篇博客的有些帮助
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查看结果吧。