首页 文章

webpack可以从vanilla js文件的顶层公开var吗?

提问于
浏览
0

我想使用像这样结构化的javascript文件中的var ...

var thing = 123;

我添加了像 yarn add git://repo 这样的文件的repo,我需要在我的webpack构建的项目中访问 thing . 如何配置webpack以将 thing 暴露给我的其余代码?

这似乎是公开 thing 的方式,如果这个webpack.config.js文件在模块中...

module.exports = {
   ...
   entry: './js/index.js',
   output: {
      path: './www/js/',
      filename: 'index.js',
      library: 'myLibrary',
      libraryTarget: 'var'
   ...
}

......但我不是在写模块 . 我只想从一些随机的js文件中访问var .

1 回答

  • 0

    答案是 exports-loader .

    使用纱线添加回购后,文件夹位于 node_modules/ . 添加 exports-loader

    yarn add exports-loader
    

    并向webpack.config.js添加规则:

    module.exports = {
      module: {
        rules: [
          {
            test: require.resolve(
              "./node_modules/repo-name/vanilla-file.js"
            ),
            use: "exports-loader?thing"
          },
    ...
    

    构建之后,var thing 可以从src /中的文件中获得:

    import thing from "../node_modules/repo-name/vanilla-file";
    

相关问题