【问题标题】:One of the dist file is always empty after running webpack运行 webpack 后,其中一个 dist 文件始终为空
【发布时间】:2021-09-06 06:08:01
【问题描述】:

我是 webpack 的新手,并按照快速入门指南创建和处理从 src 到 dist 的简单 js 文件。一切都好。

但是现在我试图让它处理多个 JS 文件,但遇到了一个我找不到解决方法的问题。原始教程中的文件仍然可以正常处理到 dist,但是我创建的新 JS 文件确实会在 dist 中创建一个文件,但它是空的。 JS 没有被缩小到 dist。

所以在运行下面的时候。 /dist/scripttwo.js 很好..

但是,/dist/scriptone.js 始终只是一个空文件。

webpack.config.js

const path = require('path');

module.exports = {
    entry: {
      scriptone: './src/scriptone.js',
      scripttwo: './src/scripttwo.js'
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
    },
};

scriptone.js

function sayhello() {
  return 'hello again';
}

scripttwo.js

import _ from 'lodash';

function component() {
  const element = document.createElement('div');

  // Lodash, currently included via a script, is required for this line to work
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');

  return element;
}

document.body.appendChild(component());

【问题讨论】:

    标签: javascript npm webpack


    【解决方案1】:

    那是因为您没有向scriptone.js 导出或导入任何内容。

    测试: export sayhello from scriptone.js 在文件末尾添加以下内容:

    export defalut sayhello
    

    并在scripttwo.js 中导入函数并在文件中使用它:

    import _ from 'lodash';
    import sayhello from './scriptone.js';
    
    function component() {
      const element = document.createElement('div');
    
      // Lodash, currently included via a script, is required for this line to work
      element.innerHTML = _.join(['Hello', 'webpack'], ' ') + sayhello();
    
      return element;
    }
    
    document.body.appendChild(component());
    

    【讨论】:

      【解决方案2】:

      如果您使用mode: "development" 配置,代码将在那里。

      默认情况下,Webpack 使用productionmode,Webpack v4+ 将默认在生产模式下压缩和摇树你的代码。 scriptone.js 中的代码什么都不做,没有side effects,它是死代码,Webpack 会丢弃它。这就是为什么你会得到一个空的 dist/scriptone.js 捆绑文件。

      【讨论】:

      • 感谢 slideshowp2 .. 让我了解 webpack 的缺失部分.. 干杯!
      猜你喜欢
      • 2017-08-24
      • 2019-09-13
      • 1970-01-01
      • 2014-10-30
      • 2022-11-03
      • 2014-10-21
      • 2018-07-13
      • 2021-02-24
      • 2021-03-23
      相关资源
      最近更新 更多