我有一个React应用程序,在我的应用程序中我依赖于react-scripts,因此build命令的定义像这样的"build": "react-scripts build",并且一切正常。现在,关键是在我的src目录中有一个名为wrapper.js的JS文件,这是一个独立文件,它是纯JS,没有React东西,但是它使用ES6和一些较新的功能。因此,我想做的是,我想创建一个新命令,该命令将转换并缩小该文件,并为其创建独立副本。我想使用webpack,并在项目的根目录中创建了一个webpack.config.js文件,如下所示:

const path = require('path');
const MinifyPlugin = require('babel-minify-webpack-plugin');

module.exports = {
  mode: 'production',
  output: {
    path: __dirname + 'build',
    publicPath: '/build/',
    filename: 'wrapper.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, 'src', 'wrapper.js')
        ],
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  },
  plugins: [
    new MinifyPlugin()
  ]
};


然后将以下内容添加到我的package.json文件"wrapper": "webpack"中。现在,当我运行npm run-scripts wrapper时,它会执行webpack命令,但会引发错误。输出看起来像这样:

> webpack

Hash: 0aa67383ec371b8b7cd1
Version: webpack 4.19.1
Time: 362ms
Built at: 04/06/2019 10:54:46 AM
 1 asset
Entrypoint main = wrapper.js
[0] ./src/index.js 223 bytes {0} [built] [failed] [1 error]

ERROR in ./src/index.js 22:4
Module parse failed: Unexpected token (22:4)
You may need an appropriate loader to handle this file type.
|
| ReactDOM.render(
>     <Root />,
|     document.getElementById('root'),
| );


我看到的是问题在于webpack还会尝试转换并缩小我src目录中的其他文件,因为它似乎已经击中了我的React应用程序的index.js文件。如何排除一切?或者更确切地说,如何告诉webpack仅将文件/src/wrapper.js编译和缩小,而根本不触摸其他任何内容?

最佳答案

entry对象添加到您的webpack.config.js

module.exports={
    entry: './src/wrapper.js',
    ...
}


webpack默认将entry对象指向./src/index.js

因此,如果您不覆盖entry对象,则webpack会将文件捆绑在./src/index.js

更新资料

正确指向output目录

output: {
    filename: 'wrapper.js',
    path: path.resolve(__dirname, 'build')
}

09-25 18:31
查看更多