如何使用 webpack 添加 js 文件?

How to add a js file with webpack?

我正在阅读这个 webpack 教程:

https://webpack.github.io/docs/usage.html

它说它捆绑了 src 文件和 node_modules。如果我想在那里添加另一个 .js 文件,我该怎么做?这是一个 thirdpartyjs 文件,它不是源代码的一部分,也不属于 node_modules 文件的一部分。这是我目前的 webpack.config.js:

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: [
        'react-hot-loader/patch',
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        './app/app.js'
    ],
    output: {
        path: path.resolve(__dirname, "dist"),
        publicPath: "/dist/",
        filename: "dist.js",
        sourceMapFilename: "dist.map"
    },
    devtool: 'source-map',
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('development')
            }
        }),
    ],
    module: {
        loaders: [{
            loader: 'babel',
            exclude: /node_modules/
        }]
    },
    devServer: {
        inline: true
    },
    node: {
        fs: "empty"
    },
    watch: false
}

代码的起点是配置中的 entry 字段。在您的配置入口点是文件列表。 webpack 搞定所有,解决它们的依赖并输出到一个文件中。

添加第三方脚本有两种选择:

  • 在条目列表前添加文件路径app.js
  • 需要此文件来自 app.js

回应德米特里的回答:

  • add the file path to entry list before app.js

这会导致您将为每个入口点获得一个捆绑的 .js 文件,这可能是您不想要的。

  • require this file from app.js

如果 app.js 是动态编写的,您可能无法访问它,或者出于任何原因您可能不想编辑 app.js

另一种选择:

您可以使用 webpack-inject-plugin 将任何 JS 代码作为字符串注入到由 webpack 创建的生成的 .js 包中。通过这种方式,您可以读取要作为字符串注入的文件(例如 nodejs 中的 fs.readFile)并使用插件注入它。

不使用任何额外插件的另一种解决方案:

//Webpack.config.js
entry: {
  main: './src/index',
 /**
 /* object is passed to load script at global scope and exec immediately
 /* but if you don't need then simply do:
 /* myCustomScriptEntry: './src/myCustomScript'
 */
  myCustomScriptEntry: { 
    import: './src/myCustomScript',
    library: {
      name: 'myCustomScriptEntry',
      type: 'var',
    },
  },
},
new HtmlWebpackPlugin({
  template: './public/index.html',
  excludeChunks: ['myCustomScriptEntry'], //exclude it from being autoreferenced in script tag
  favicon: './public/favicon.svg',
  title: 'Alida',
}),

//index.html
<script type="text/javascript" src="<%= compilation.namedChunks.get('myCustomScriptEntry').files[0] %>"></script>