美文网首页
Webpack构建项目

Webpack构建项目

作者: 林初盛 | 来源:发表于2017-02-15 10:58 被阅读1430次

    1.构建项目 NewProgram
    2.安装npm 生成 package.json

    {  "name": "y",
      "version": "1.0.0",  
    "description": "", 
     "main": "index.js",  
    "scripts": {    
      "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "", 
     "license": "ISC",  
    "dependencies": {    
      "react": "^0.14.8",    
      "react-dom": "^0.14.8",    
      "react-router": "^2.0.1",    
      "reflux": "^0.4.0"  },
    "devDependencies": {
      .... 
    }
    

    3.通过npm 去下载组件,安装依赖

    webpack -g               `全局安装`
    webpack-dev-server       `webpack也有一个web服务器`
    react react-dom --save   `安装 React`
    babel-core babel-loader babel-preset-es2015 babel-preset-react --save-dev `安装 Babel 的 loader 以支持 ES6 语法:`
    browser-sync
    

    4.webpack配置文件

    // webpack.config.js
    
    var path = require('path');
    /**
    webpack 使用一个名为 webpack.config.js的配置文件, 现在在你的项目根目录下创建该文件. 
    我们假设我们的工程有一个入口文件 app.js, 该文件位于 app/ 目录下, 
    并且希望 webpack 将它打包输出为 build/ 目录的 bundle.js文件. 
    **/
    module.exports = {
      entry: path.resolve(__dirname, 'app/app.js'),
      output: {
    /**path: 打包文件存放的绝对路径
    publicPath: 网站运行时的访问路径
    filename:打包后的文件名**/
        path: path.resolve(__dirname, 'build'),
        filename: 'bundle.js',
        publicPath:'/build/' 
      },
    //配置 webpack.config.js来使用安装的 loader.
      module: {
        loaders: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          loader: 'babel',
          query: {presets: ['es2015','react']}
        },]
      }
    };
    
    
    

    5.创建 app/app.js文件

    // app.js
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    
    /1
    ReactDOM.render(     
      <div>你好 世界</div>,    
      document.querySelector('#ROOT1'));
    
    /2
    ReactDOM.render(    
      React.createElement('div', null,        
        React.createElement('div', null,            
          React.createElement('h1', {}, '你好')       
         )    
      ),    document.getElementById('ROOT2'));
    
    /3
    export default class HelloWorld extends React.Component {    
        render() {        
          return (            
            <div>成功 ohye</div>    
            )    }}
    
    ReactDOM.render(<HelloWorld/>,document.getElementById('ROOT3'));
    
    

    6.创建 build/index.html
    其中 script 引入了 bundle.js, 这是 webpack 打包后的输出文件.

    <!DOCTYPE html>
    <head>
      <meta charset="UTF-8">
      <title>Hacker News Front Page</title>
    </head>
    <body>
      <div id="ROOT1"></div>
      <div id="ROOT2"></div>
      <div id="ROOT3"></div>
      <script src="./build/bundle.js"></script> 
    </body>
    </html>
    

    在命令行运行webpack .webpack就会按照设置,在build目录下生成完整的JS文件.但是并不能实时反馈和查看.

    打包:
    修改package.json文件后, npm run build 相当于 webpack,npm run start相当于webpack-dev-server

    "scripts": {  "start": "webpack-dev-server",  "build": "webpack"}
    

    服务器运行: webpack-dev-server (开启服务器运行)
    运行 webpack打包, 运行 webpack-dev-server 会启动localhost:8080服务器.
    访问 http://localhost:8080/build/index.html, 如果一切顺利, 你会看到打印出了 It works
    .

    .


    热启动

    1.npm 添加webpack-dev-serverreact-hot-loader这两个库

    npm install --save-dev webpack-dev-server react-hot-loader
    

    2.修改webpack配置文件

    entry: [ 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', './js/index.js' ] //入口
    },
    

    通过这种方式指定资源热启动对应的服务器,然后需要配置react-hot-loader到loaders的配置当中,比如我的所有组件代码全部放在scripts文件夹下:

    { test: /\.js?$/, loaders: ['react-hot', 'babel'], include: [path.join(__dirname, 'scripts')]}
    
    //test 后缀  loaders 名字  include 在哪个位置
    
    { test: /\.js?$/, loaders: 'react-hot', exclude: /node_modules/}
    
    

    最后配置一下plugins,加上热替换的插件和防止报错的插件:

    plugins: [
    
      new webpack.HotModuleReplacementPlugin(),
    
      new webpack.NoErrorsPlugin() 
    ]
    
    var webpack = require('webpack');
    var path = require('path');
    module.exports = {    
      entry: [      
       'webpack/hot/dev-server',        
      'webpack-dev-server/client?http://localhost:3000',        
      './js/app.js'   
      ],    
      output: {       
         path: path.resolve(__dirname, 'build'),        
        filename: 'bundle.js',        
        publicPath:'/build/'    
      },    
      plugins: [        
        new webpack.HotModuleReplacementPlugin(),        
        new webpack.NoErrorsPlugin()    
    ],   
      module: {        
      loaders:[           
        { test: /\.css$/, loader: 'style-loader!css-loader' },            
        { test: /\.js[x]?$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react',include: path.join(__dirname, '.') },        
    ]   
     }};
    

    这样配置就完成了,但是现在要调试需要启动一个服务器,而且之前配置里映射到http://localhost:3000
    ,所以就在本地3000端口起个服务器吧,在项目根目录下面建个server.js:

    var webpack = require('webpack');
    var WebpackDevServer = require('webpack-dev-server');
    var config = require('./webpack.config');
    new WebpackDevServer(
    webpack(config), 
    { publicPath: config.output.publicPath, 
    hot: true, 
    historyApiFallback: true
    }).
    listen(3000, 'localhost', function (err, result) 
    { 
    if (err) console.log(err); console.log('Listening at localhost:3000');
    });
    

    这样就可以在本地3000端口开启调试服务器了

    生成本地model文件 npm install (服务器使用必要过程)
    启动服务器 npm start

    相关文章

      网友评论

          本文标题:Webpack构建项目

          本文链接:https://www.haomeiwen.com/subject/bgzvyttx.html