webpack2的一些使用入门

首先创建一个webpack文件夹我取名叫webpackVue(为了后续把vue集成进来)

1、首先用npm初始化一下,在这个目录下,执行npm init

2、npm install webpack --save-dev

3、安装一些自己要用到的loader(加载css,js,scss等文件): npm install style-loader css-loader sass-loader node-sass --save-dev

4、安装一些自己需要的plugin(html自动更行):npm install html-webpack-plugin --save-dev

5、安装webpack-dev-server(运行在服务器上,可以在网页中访问): npm install webpack-dev-server --save-dev

5、创建需要打包的html,css,js

index.html

<!doctype html>
<html>
  <head>
    <title></title>
    <meta charset="utf-8" />

  </head>
  <body>
  hello world! <script src="build/bundle.js"></script> </body> </html>

index.js

require('./test.scss')

test.scss

body {
    color: red;
}

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const path = require('path');
module.exports = {
    entry: "./index.js", // 入口文件

    // 输出文件 build下的bundle.js
    output: {
      path: path.resolve(__dirname, 'build'),
      filename: "bundle.js"
    },

    // 使用loader模块
    module: {
      loaders: [
        {test: /\.css$/, loader: "style-loader!css-loader"}
      ],
      loaders: [
        {test: /\.scss$/, loader: "style-loader!css-loader!sass-loader"}
      ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html',
        })
    ],
};  

然后使用npm run build命令进行打包

不要使用webpack命令,webpack没有全局安装,npm run build 会到node-modules里面去找webpack,在webpack根目录下执行webpack命令。

如果要使用webpack命令,要在webpack安装根目录下执行,或者全局安装后,指定node-path,不推荐全局安装webpack    

最后的运行结果如下:

 

 

 

posted on 2017-10-17 11:37  杨龙飞  阅读(144)  评论(0编辑  收藏  举报

导航

Fork me on GitHub