如何使用Webpack将所有导入的依赖项捆绑在一个文件中?

时间:2018-02-02 11:47:18

标签: javascript web webpack babeljs babel

我有以下目录结构...

root
│   package.json
│   webpack-client.config.js
│   webpack-server.config.js
│   yarn.lock
├───assets
│   └───js
│           index.js
├───dist
│   │   header.html
│   │   hotel-details.html
│   │   hotel-list.html
│   │   index.html
│   │   server.js
│   │   
│   └───static
│       └───j
│               index.js
├───node_modules
│   └...
├───server
│       database.js
│       index.js
└───views
        header.html
        hotel-details.html
        hotel-list.html
        index.html

我想将Webpack用于两件事。

  1. 缩小并捆绑服务器端JS - 使用dist/server.js作为入口点将捆绑包导出到server/index.js。我使用下面提供的webpack-server.config.js来实现这一目标。

  2. 缩小每个views/*.html文件并将其导出到dist/v/*.html。如果html文件包含<script>个代码,我想从这些文件中创建缩小的捆绑包并将其导出到dist/static/j/[html_filename].js

    • 我正在努力解决这个问题。我设法缩小.html文件并将其.js文件导出到dist/static/j/[html_filename].js。但是,我无法使用html中的.js文件,因为它使用requireimport等语法。我提供了assets/js/index.jsdist/static/j/index.js的内容。
  3. webpack-client.config.js

    var path = require("path");
    var fs = require("fs");
    
    var htmlFiles = {}; 
    fs.readdirSync(path.join(__dirname, 'views'))
      .filter(f => (path.parse(f).ext.toLowerCase() === '.html'))
      .forEach(f => {
        var name = path.parse(f).name;
        htmlFiles[name] = path.join(__dirname, 'views', f);
      });
    
    module.exports = {
      module: {
        rules: [
          { 
            test: /\.html$/, 
            use: [
              { loader: 'file-loader', options: { name: '[name].[ext]', emitFile: true }},
              { loader: 'extract-loader' },
              { 
                loader: 'html-loader',
                options: { 
                  minimize: true,
                  attrs: ['script:src']
                }
              },
            ]
          },
          {
            test: /\.js$/,
            use: [
              { 
                loader: 'file-loader', 
                options: { 
                  name: 'static/j/[name].[ext]',
                  publicPath: (p) => p.replace('static/', '')
                }
              },
              {
                loader: 'babel-loader',
                options: {
                  presets: [
                    [
                      "babel-preset-env", {
                        "targets": {
                          "chrome": 52
                        }
                      }
                    ]
                  ]
                }
              },
            ]
          }
        ]
      },
      target: 'web',
      watch: true,
      entry: htmlFiles,
      output: {
        path: path.join(__dirname, "dist"),
        filename: '[name].html.js'
      }
    };
    

    webpack-server.config.js

    var path = require("path");
    var fs = require("fs");
    const MinifyPlugin = require('babel-minify-webpack-plugin');
    
    var nodeLibs = {};
    fs.readdirSync(path.join(__dirname, 'node_modules'))
      .filter(x => x !== '.bin')
      .forEach(mod => { nodeLibs[mod] = 'commonjs ' + mod; });
    
    module.exports = {
      externals: nodeLibs,
    
      module: {
        rules: [
          {
            test: /\.js$/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['babel-preset-env']
              }
            }
          }
        ] 
      },
      plugins: [
        new MinifyPlugin()
      ],
      context: __dirname,
      entry: {
        server: "./server/index.js"
      },
      target: "node",
      output: {
        path: path.join(__dirname, "dist"),
        filename: "server.js"
      }
    };
    

    assets/js/index.js

    import $ from '../../node_modules/jquery';
    
    let scrollEnabled = true;
    
    window.setScrollEnabled = (scrollEnabled) => {
      $('body').css({backgroundColor: 'red'});
      console.log('isScrollEnabled:', scrollEnabled);
    }
    

1 个答案:

答案 0 :(得分:1)

您希望将JS文件用作入口点,而不是HTML。 documentation for entry points可能有用。