webpack Babel如何复制transpiled文件,如果我不使用导入/要求

imzjd6km  于 2022-12-08  发布在  Babel
关注(0)|答案(2)|浏览(154)

我的项目中有一个名为test.js的文件
我没有在任何地方导入/需要它,这意味着我的webpack不会为该js文件调用babel-loader

问题:我想要的是将test.js移动到/dist文件夹中,但作为一个已编译/已转换的文件。最佳实践是什么?
**我尝试过的:**我尝试过使用copy-webpack-plugin并在复制文件之前使用它的转换参数,但是我似乎找不到好的babel包。

{
    from: 'test.js',
        to: '/dist/test.js',
            transform(content, path) {
        //what do I write here? 
    },
}
nhaq1z21

nhaq1z211#

我能想到的最简单的方法是使用几个入口点,如下所示:

{
    entry: {
        a: "./your-main-stuff",
        b: "./your-single-file",
    },
    output: {
        path: path.join(__dirname, "dist"),
        filename: "[name].js"
    }
}

这将创建您的a.js主包和__dirname/dist文件夹中的b.js文件,如果您使用相应的加载程序,这两个文件都将被传输。
从copy-webpack-plugin文档section中可以看到:
webpack-copy-plugin并非设计用于复制构建过程中生成的文件;而是复制源代码树中已经存在的文件,作为构建过程的一部分。
所以它似乎很难(如果可能的话)使它移动transpiled文件。

更新。如果您想将文件输出到不同的文件夹而不更改您的src文件夹,需要其他工具。对于您的情况(只有1个文件),我会编写一个简单的脚本,并将其添加到package.json脚本部分,并结合webpack调用,如:

"scripts": {
     "dev": "webpack && babel path-to-script.js --out-file path-to-script-compiled.js"
 }
0g0grzrc

0g0grzrc2#

就像前面的答案一样,最初我使用package.json中的“scripts”条目来运行babel。但是由于一些原因,我想使用webpack 5来完成这项工作。因此,在webpack-copy-plugin失败后,我进行了大量的挖掘,我使用了this solution

let config = {
    entry: [
        glob.sync(srcDir + '/**/*.js') // get all .js files from the source dir
    ],
    output : {
        filename : '[name].rem.js',  // webpack wants to bundle - it can bundle here ;) 
        path: outDir
    },
    resolve: {
        alias: {
            'app': appDir
        }
    },
    plugins: [
        new RemoveEmptyScriptsPlugin({extensions: ['js'], scriptExtensions: /\.rem\.js/}) // for all .js source files that get bundled remove the bundle .rem.js file
    ],
    module: {
        rules:[{
            test: /\.jsx?$/,
            type: 'asset/resource', // get webpack to take it out instead of bundling
            generator: {
                filename: ({filename}) => filename // return full file name so directory structure is preserved
            },
            use: {
                loader: 'babel-loader',
                options: {
                    targets: { node: 16 },
                    presets: [
                        ['@babel/preset-env', { modules: 'commonjs' /* transpile import/export */}],
                    ]
                }
            }
        }]
    }
};
// Since the code does not go through the full pipeline and imports are not getting resolved, aliases will remain in the code.
// To resolve them it takes to hack the aliases object into the babel config
config.module.rules[0].use.options.plugins.push(['babel-plugin-webpack-alias-7', {config: {resolve: {alias: config.resolve.alias}}}];

而且它做得很好,但要注意,它需要使用两个插件的补丁版本(除非补丁已经合并)!

相关问题