webpak初学

webpack

前面我们建立了一个项目, 现在我们在这个项目开始webpack学习

首先我们需要安装webpack,按照官网推荐安装方式,我们采用局部安装,进入static文件夹,运行安装命令:

npm init -y 
npm install --save-dev webpack
安装后在stati目录下会生成一个package.json文件和一个node_modules文件夹


新建目录css、js、images和dist,并新建文件webpack.config.js

前面我们已经在页面上输出路hello world, 现在我们使用webpack输出hello world

在js文件夹下新建文件index.js,输入代码:

import _ from 'lodash';

function component(){
  var element = document.createElement('div')
  element.innerHTML = _.join(['hello', 'world'], ' ');
  element.classList.add('hello');

  return element;
}
document.body.appendChild(component())



在webpack.config.js中输入代码:

const path = require('path');

module.exports = {
  entry: './js/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};




在package.json的scripts中加入代码:
"build": "webpack"

"scripts": {

    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },




回到templates目录,在在index.html中输入代码:

<html>
 <head>
   <title>Getting Started</title>
 </head>
 <body>
   <script src="{{ url_for('static', filename='dist/bundle.js') }}"></script>
 </body>
</html>

然后在node_modules目录下运行命令

npm run build

运行项目即可看到webpack输出的hello world


接下来为hello world添加样式

还是在node_modules目录下运行命令:

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

安装好后修改webpack.config.js

在里面加入代码:

module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }

    ]
  }

const path = require('path');

module.exports = {
  entry: './js/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          'style-loader',
          'css-loader'
        ]
      }

    ]
  }
};

在css目录下写下hello的样式,

.hello{....}

再次运行npm run build,hello就被添加上路样式

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值